Spring Boot Hibernate 在多对多保存时出现重复键值违反唯一约束

huangapple 未分类评论44阅读模式
英文:

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 = &quot;uuid2&quot;)
    @GenericGenerator(name = &quot;uuid2&quot;, strategy = &quot;uuid2&quot;)
    @Type(type = &quot;uuid-char&quot;)
    private UUID id;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = &quot;a_b&quot;,
            joinColumns = @JoinColumn(name = &quot;a_id&quot;),
            inverseJoinColumns = @JoinColumn(name = &quot;b_id&quot;))
    public Set&lt;B&gt; bs;

...
}

B.java:

@Entity
public class B {

    @Id
    @NotNull
    private String bId;

    @ManyToMany(mappedBy = &quot;bs&quot;)
    private Set&lt;A&gt; 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 &quot;b_pkey&quot;
  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?

huangapple
  • 本文由 发表于 2020年4月10日 10:05:29
  • 转载请务必保留本文链接:https://java.coder-hub.com/61132989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定