简体   繁体   中英

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

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.

您不应该使用@ElementCollection来收集实体,它用于收集可嵌入或简单类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM