2

Good time of day! I have some problem with creating a Many-To-Many relation with Hibernate. It creates in join table unique constraint:

"uk_bapa98k9j6y66sqniad6k680l" UNIQUE CONSTRAINT, btree (users_id)

So I can have only one row for specific user in this table, attempt to insert another one row with the same user_id causes error:

ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: duplicate key value violates unique constraint "uk_bapa98k9j6y66sqniad6k680l" Подробности: Key (users_id)=(1) already exists

How can I forbid Hibernate to add unique constraint in this table?

@Entity
@Table(name="Projects", schema="public")
public class Project implements Serializable {
...
    @Id
    @GenericGenerator(name="increment", strategy="org.hibernate.id.IncrementGenerator")
    @GeneratedValue(generator="increment")
    @Column(name="project_id")
    public Long getId() {
        return this.id;
    }
...
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="project_users", joinColumns=@JoinColumn(name="projects_id"), inverseJoinColumns=@JoinColumn(name="users_id"))
    @ElementCollection(targetClass=User.class)
    public Set<User> getUsers()
    {
        return users;
    }


@Entity
@Table(name="Users")

public class User implements Serializable {
...
    @Id
    @GenericGenerator(name="increment", strategy="org.hibernate.id.IncrementGenerator")
    @GeneratedValue(generator="increment")
    @Column(name="user_id")
    public Long getId() {
        return this.id;
    }
...
    @ManyToMany(mappedBy="users")
    public Set<Project> getProjects()
    {
        return projects;
    }

2 Answers2

1

You should not use @ElementCollection for collection of entities, it is used for collection of embeddable or simple types.

veljkost
  • 1,748
  • 21
  • 25
  • If i delete this annotation, it causes new exception: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist – Daniil Solodukhin Oct 06 '16 at 14:46
  • This answer should be marked as a solution. took me a while to find. As a reference https://stackoverflow.com/questions/8969059/difference-between-onetomany-and-elementcollection – Daniel Diogo Jan 28 '20 at 00:41
0

When you annotate an entity field with @Id, the Id must be unique. So the USERS.user­_id should have an Unicity constraint regardless of your Many to Many relationship.

Nils Renaud
  • 554
  • 4
  • 20