Hibernate : How to Join 3 tables in one join table by Annotation?

∥☆過路亽.° 提交于 2019-12-11 05:24:21

问题


I have some roles, users and applications I want to create a mapping hibernate of this table :

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

for an application, a role can have many users and a user can of many roles.

I try this mapping :

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<>();

Unfortunately, this is not working in my case because in java, the key of a Map must be unique.

With this mapping, we can have only one user for a role and an application.


回答1:


try this implementation :

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


来源:https://stackoverflow.com/questions/38591170/hibernate-how-to-join-3-tables-in-one-join-table-by-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!