Spring Boot Hibernate Duplicate Key Value Violates Unique Constraint at Many to Many Save

Viewed 1035

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?

0 Answers
Related