Daniil Solodukhin
Daniil Solodukhin

Reputation: 53

Hibernate Many-To-Many relation creates unnecessary unique constraint

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;
    }

Upvotes: 2

Views: 1223

Answers (2)

veljkost
veljkost

Reputation: 1932

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

Upvotes: 1

Nils Renaud
Nils Renaud

Reputation: 584

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.

Upvotes: 0

Related Questions