具有相同列名的对象的ManyToMany关系用于id' s

时间:2017-05-16 08:59:30

标签: java spring

我有两个课程:UserRole

Role定义为:

@Entity
@Table(name="Role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="RoleId")
    private long id;
    ....
}

User定义为:

@Entity
@Table(name="User")
public class User implements UserDetails { 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="UserId")
    private long id;

    @ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinTable(name = "User_Role", 
                joinColumns = @JoinColumn(name = "Id"), 
                inverseJoinColumns = @JoinColumn(name = "Id"))
    private Set<Role> roles;
    .....
   }

显然有两列具有相似名称的id会引发以下错误:

Repeated column in mapping for collection: com.myproject.security.model.User.roles column: id

我该如何解决这个问题?当我将列重命名为RoleIdUserId时,没有错误。

2 个答案:

答案 0 :(得分:2)

joinColumns和inverseJoinColumns将是表User_Role中的列,在同一个表中不能有两个具有相同名称的列

答案 1 :(得分:1)

You have explicitly told Hibernate (or whatever JPA implementation you're using) that both user ID and role ID should be stored in the column named Id in the table named User_Role.

Since they reference different entities they need to be different columns, this is probably what you want to do:

@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name = "User_Role", 
            joinColumns = @JoinColumn(name = "UserId"), 
            inverseJoinColumns = @JoinColumn(name = "RoleId"))
private Set<Role> roles;

This way you will store the ID of the user in UserId and the ID of the role in RoleId.