我有2个人:
@Entity
@Table(name="product")
public class Product {
private Long id;
private Set<Upgrade> upgrade;
@Id
@Column(name="id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToMany(mappedBy = "products",
targetEntity = Upgrade.class,
cascade = CascadeType.REFRESH,
fetch = FetchType.EAGER)
public Set<Upgrade> getUpgrade() {
return upgrade;
}
public void setUpgrade(Set<Upgrade> upgrade) {
this.upgrade = upgrade;
}
}
和
@Entity
@Table(name="upgrade")
public class Upgrade {
private Long id;
private Set<Product> products;
@Id
@Column(name="id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToMany(targetEntity = Product.class, cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinTable(name = "upgrade_product",
joinColumns = @JoinColumn(name = "upgrade_id"),
inverseJoinColumns = @JoinColumn(name="product_id"))
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
}
我的数据会创建这些数据,以便产品包含一组多个升级。
即。 P1 {U1,U2,U3,U4} P2 {U1,U3,U5,U7}
如果我删除升级,那么一切都很好。它刚刚从产品中删除。 但是,如果我删除了某个产品,那么它会尝试删除所有链接的升级。
如何让它能够删除产品并保留升级。
答案 0 :(得分:3)
在删除Product
之前,请清除其Set<Upgrade>
并保存Product
。类似的东西:
public void delete(Product p)
{
p.setUpgrade(Collections.emptySet());
entityManager.remove(entityManager.merge(p));
}