Hibernate:如何通过Annotation在一个连接表中连接3个表?

时间:2016-07-26 13:26:34

标签: java hibernate many-to-many jointable

我有一些角色,用户和应用程序 我想创建一个这个表的映射休眠:

CREATE TABLE role_application_user (
  role_identifier INTEGER not null,
  application_identifier INTEGER not null,
  user_identifier INTEGER not null,
  KEY FK_role_identifier (role_identifier),
  KEY FK_application_identifier(application_identifier),
  KEY FK_user_identifier (user_identifier),
  CONSTRAINT FK_role_identifier FOREIGN KEY (role_identifier) REFERENCES role (identifier),
  CONSTRAINT FK_application_identifier FOREIGN KEY (application_identifier) REFERENCES application (identifier),
  CONSTRAINT FK_user_identifier FOREIGN KEY (user_identifier) REFERENCES users (login)
);

对于应用程序,角色可以包含许多用户,而用户可以拥有多个角色。

我尝试这种映射:

Application.java

@JoinTable(name = "role_application_user",
           joinColumns = @JoinColumn(name = "application_identifier"),
           inverseJoinColumns = @JoinColumn(name = "user_identifier"))
@MapKeyJoinColumn(name = "role_identifier")
@ElementCollection
private Map<Role, User> userByRole = new HashMap<>();

不幸的是,这在我的情况下不起作用,因为在java中,Map的键必须是唯一的。

通过此映射,我们只能为角色和应用程序提供一个用户。

1 个答案:

答案 0 :(得分:0)

试试这个实现:

@Entity
public class User{
    @OneToMany
    private List<RoleInApplication> rolesInApplications;
}

@Entity
public Class Role{
   @OneToMany
    private List<RoleInApplication> rolesInApplications;
}

@Entity
public class RoleInApplication{
    @ManyToOne
    private User user;
    @ManyToOne
    private Role role;
    @ManyToOne
    private Application application;
}

@Entity
public Class Application{
   @OneToMany
   private List<RoleInApplication> rolesInApplications;
}