英文:
Spring Boot Hibernate Duplicate Key Value Violates Unique Constraint at Many to Many Save
问题
A.java:
@Entity
public class A {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Type(type = "uuid-char")
private UUID id;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "a_b",
joinColumns = @JoinColumn(name = "a_id"),
inverseJoinColumns = @JoinColumn(name = "b_id"))
public Set<B> bs;
...
}
B.java:
@Entity
public class B {
@Id
@NotNull
private String bId;
@ManyToMany(mappedBy = "bs")
private Set<A> as;
...
}
AService.java:
...
public void save(A a) {
aRepository.save(a);
}
...
Both A and B entities are persisted when I create an A which has a set of B. However, it throws an error for the second time:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "b_pkey"
Detail: Key (b_id)=(2) already exists.
What I am trying to do is when creating an A entity (without having id fields populated by me) which has a set of B (which has id fields populated by me):
Creating Bs if there is not already a record for a B and do not create if it already exists with the given id.
How to achieve it?
英文:
A.java:
@Entity
public class A {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Type(type = "uuid-char")
private UUID id;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "a_b",
joinColumns = @JoinColumn(name = "a_id"),
inverseJoinColumns = @JoinColumn(name = "b_id"))
public Set<B> bs;
...
}
B.java:
@Entity
public class B {
@Id
@NotNull
private String bId;
@ManyToMany(mappedBy = "bs")
private Set<A> as;
...
}
AService.java:
...
public void save(A a) {
aRepository.save(a);
}
...
Both A and B entities are persisted when I create an A which has a set of B. However, it throws an error for second time:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "b_pkey"
Detail: Key (b_id)=(2) already exists.
What I am trying to do is when creating an A entity (without having id fields populated by me) which has a set of B (which has id fields populated by me):
Creating Bs if there is not already a record for a B and do not create if already exists with given id.
How to achieve it?
专注分享java语言的经验与见解,让所有开发者获益!
评论