我有两个类--USER和ROLE . 数据库中有相应的表,以及一个名为USER_ROLE的表,用于链接这两个表 .

USER在列“ id ", and a composite unique key on columns " realm " and " realm_user_id ". ROLE has a primary key on column " role_id ”上有一个主键

USER_ROLE有3列 - role_idrealmrealm_user_id .

role_id 在ROLE表中引用 role_id ,( realm,realm_user_id )引用USER中的复合键 . 我没有't have access to the DB, so I can' t更新架构 .

用户和角色之间存在多对多关系 . 我希望能够在User上调用getRoles(),在Role上调用getUsers() .

class 用户:

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

        ..other fields..

        @ManyToMany(fetch = FetchType.LAZY, targetEntity=Role.class)
        @JoinTable(name = "USER_ROLE", 
        joinColumns = { 
          @JoinColumn(name = "realm", nullable = false, updatable = false),
          @JoinColumn(name = "realm_user_id", nullable = false, updatable = false)
        },
        inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
        private Set<Role> roles;

class 角色:

@ManyToMany(fetch = FetchType.LAZY,
        cascade={CascadeType.PERSIST,CascadeType.MERGE},
        targetEntity=User.class
    )
    @JoinTable(name = "USER_ROLE", 
    joinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) }, 
    inverseJoinColumns={
            @JoinColumn(name="realm",nullable=false, updatable=false),
            @JoinColumn(name="realm_user_id",nullable=false, updatable=false)
    })
    private Set<User> users;

我收到以下错误:

A Foreign key refering User from Role has the wrong number of column. should be 1

我尝试创建一个包含realm和realm_user_id的单独类,在 @IdClass 注释中引用,但由于User已经在 id 上有一个主键而失败了 . 我尝试使用mappedBy注释,但这也不起作用 .