gpt4 book ai didi

java - 如何从 JPA 中的父实体记录中删除子实体?

转载 作者:行者123 更新时间:2023-11-30 05:24:28 25 4
gpt4 key购买 nike

我有 Product 实体和 ProductRating 实体,每个 Product 可以有许多 ProductRating 。当 Product 被删除时,我也想删除关联的评级,但到目前为止没有任何作用(也将 orphanRemoval 设置为 true)...

类(class):

@Getter
@Setter
@Entity
@Table(name = "PRODUCT")
public class Product extends AbstractEntity<Long> {

@Column(nullable = false)
private String name;

private String description;

@Column(nullable = false)
@Min(value = 0)
private Float cost;

@OneToMany(mappedBy = "product",
orphanRemoval = true, cascade = CascadeType.PERSIST,
fetch = FetchType.EAGER)
//@OnDelete(action = OnDeleteAction.CASCADE)
@Fetch(value = FetchMode.SELECT)
private Set<ProductRating> productRatings;

}
@Getter
@Setter
@Entity
@Table(name = "PRODUCT_RATING")
public class ProductRating extends Rating {

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "product_id")
@NotNull(message = "Rating must be in context of Product")
private Product product;
}

删除产品后,评分仍保留在已删除的产品 ID 中

AbstractEntity 实现:

@Getter
@Setter
@MappedSuperclass
public abstract class AbstractEntity<I> implements Serializable {
private static final long serialVersionUID = 1700166770839683115L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", unique = true, nullable = false)
private I id;

}

最佳答案

@OneToMany关系中,您需要添加级联类型删除:cascade = {CascadeType.PERSIST, CascadeType.REMOVE}

或者,如果您不介意拥有所有级联类型,您可以输入:cascade = CascadeType.ALL

编辑:

还要检查数据库中 Product 主键的名称。它应该与 ProductRating

@JoinColumn 注释中的定义匹配

Product 类的属性 id 的默认数据库字段为 product_id。但是,您已在 AbstractEntity 中将 id 定义为 name = "ID",因此 @JoinColumn 应该类似于:@JoinColumn(name = "ID")

关于java - 如何从 JPA 中的父实体记录中删除子实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58936241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com