在我的应用程序中,每个客户都可以拥有多个帐户。我有以下数据结构(为简洁省略了很多):
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@Id
@Column(length = 36, name = "CUSTOMER_ID", nullable = false, unique = true)
private String id;
@OneToMany
@JoinColumn(name = "OWNER_ID", referencedColumnName = "CUSTOMER_ID")
private List<Account> accounts;
}
@Entity
@Table(name = "ACCOUNT")
public class Account {
@Id
@Column(length = 36, name = "ACCOUNT_ID", nullable = false, unique = true)
private String id;
@Column(name = "OWNER_ID", nullable = false)
private String ownerId;
}
如果我使用JPA删除客户,例如
entityManager.remove(customer);
它尝试使用null更新相关的ACCOUNT.OWNER_ID字段。 OWNER_ID不可为空,因此抛出JDBCException并回滚事务。
我需要实现的是相关的ACCOUNT行被删除(如果有的话)。我怎么能这样做?
谢谢
更新:我用
尝试了@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
但它不会改变行为:仍然尝试使用null更新。
答案 0 :(得分:0)
我认为您需要使用级联才能删除子元素。试试这个:
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "OWNER_ID", referencedColumnName = "CUSTOMER_ID")
private List<Account> accounts;
您还应该通过ManyToOne关系而不是字符串ID引用您帐户中的客户。我认为这应该可以解决您的问题:
@Column(name = "OWNER_ID", nullable = false)
@ManyToOne
private Customer owner;