简体   繁体   English

Hibernate多对多关系会创建不必要的唯一约束

[英]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. 我在使用Hibernate创建多对多关系时遇到了一些问题。 It creates in join table unique constraint: 它在连接表中创建唯一约束:

"uk_bapa98k9j6y66sqniad6k680l" UNIQUE CONSTRAINT, btree (users_id) “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: 因此,此表中的特定用户只能有一行,尝试插入另一行,同一个user_id会导致错误:

ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: duplicate key value violates unique constraint "uk_bapa98k9j6y66sqniad6k680l" Подробности: Key (users_id)=(1) already exists 错误org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 错误:重复键值违反唯一约束“uk_bapa98k9j6y66sqniad6k680l”Подробности:Key(users_id)=(1)已存在

How can I forbid Hibernate to add unique constraint in this table? 我怎样才能禁止Hibernate在此表中添加唯一约束?

@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. 使用@Id注释实体字段时,Id必须是唯一的。 So the USERS.user_id should have an Unicity constraint regardless of your Many to Many relationship. 因此,无论您的多对多关系如何,USERS.user_id都应具有Unicity约束。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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