I'm trying to undestand @JoinTable for @OneToMany relations using JPA. I have the relation above:
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
My problem is: I can create a client with as many contacts as I want, I can remove contacts, but when I try to update one contact of the client or add a contact after the client is created I'm getting the following foreign key error:
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]
It seams to me that hibernate is trying to re-insert the contact in the joinTable, what I'm doing wrong? *I'm updating the entity with entityManager.merge()
.
I'm using Hibernate 5.1.0, JPA 2.1.
I'm trying to avoid using mappedBy or JPA 2.1 @OneToMany relation with no JoinTable, because I have other entities that contains Contacts as well