gpt4 book ai didi

java - @JoinTable 更新时出现外键错误

转载 作者:行者123 更新时间:2023-11-30 08:34:19 25 4
gpt4 key购买 nike

我正在尝试使用 JPA 理解 @JoinTable 对 @OneToMany 关系的理解。我有上面的关系:

CLIENT

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;

}

CONTACT

public class Contact {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
private String number;

}

Problem Description

我的问题是:我可以创建一个包含任意多个联系人的客户端,我可以删除联系人,但是当我尝试更新客户端的一个联系人或在创建客户端后添加一个联系人时,我'我收到以下外键错误:

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 关系,因为我还有其他包含联系人的实体

最佳答案

您必须重新定义实体中的 hashcode 和 equals 方法。

来自 Oracle 文档 https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

现在让我们看看如果您尝试这种情况会发生什么:

     Client client = new Client();
entityManager.persist(client);
Contact contact = new Contact();
entityManager.persist(contact);
client.getContacts.add(contact);
entityManager.merge(client);

Contact contact2 =entityManager.find(Contact.class,contact.getId());
//and now Unique index or primary key violation will appear
//because you are using the default equals and hashcode implementation
//adding contact2 will not replace the old one
client.getClients().add(client2);
entityManager.merge(client);//Unique index or primary key violation

为避免这种情况,您必须为您的 jpa 实体实现 Equals 和 HashCode。

查看这些链接 https://vladmihalcea.com/hibernate-facts-equals-and-hashcode/The JPA hashCode() / equals() dilemma

关于java - @JoinTable 更新时出现外键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885866/

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