我正在尝试使用JPA取消@JoinTable以获取@OneToMany关系。我有上述关系:
客户端
public class Client {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinTable(name = "client_contact",
joinColumns = @JoinColumn(name = "client_id"),
foreignKey = @ForeignKey(name = "fk_client_contact__client"),
inverseJoinColumns = @JoinColumn(name = "contact_id"),
inverseForeignKey = @ForeignKey(name = "fk_client_contact__contact"))
private Set<Contact> contactNumbers;
}
联系
public class Contact {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
private String number;
}
问题描述
我的问题是:我可以创建一个拥有尽可能多的联系人的客户端,我可以删除联系人,但当我尝试更新客户端的一个联系人或在创建客户端后添加联系人时我m得到以下外键错误:
Caused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY_KEY_4 ON PUBLIC.CLIENT_CONTACT(CLIENT_ID, CONTACT_ID) VALUES ( /* key:3 */ 97, 194)"; SQL statement:
insert into client_contact (client_id, contact_id) values (?, ?) [23505-175]
它告诉我,hibernate试图在joinTable中重新插入联系人,我做错了什么? *我正在使用entityManager.merge()
更新实体。
我正在使用Hibernate 5.1.0,JPA 2.1。
我试图避免在没有JoinTable的情况下使用mappedBy或JPA 2.1 @OneToMany关系,因为我还有其他包含Contacts的实体
答案 0 :(得分:0)
对于我来说,在从orphanRemoval = true
注释中移除@OneToMany
进行更新时,映射工作没有问题。
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "client_contact",
joinColumns = @JoinColumn(name = "client_id"),
foreignKey = @ForeignKey(name = "fk_client_contact__client"),
inverseJoinColumns = @JoinColumn(name = "contact_id"),
inverseForeignKey = @ForeignKey(name = "fk_client_contact__contact"))
private Set<Contact> contactNumbers;
答案 1 :(得分:0)