java - hibernate : How to Join 3 tables in one join table by Annotation?

标签 java hibernate many-to-many join

我有一些角色、用户和应用程序 我想创建该表的映射 hibernate :

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

对于应用程序,一个角色可以拥有多个用户,一个用户可以拥有多个角色。

我尝试这个映射:

应用程序.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 的键必须是唯一的。

通过此映射,我们只能让一个用户担任一个角色和一个应用程序。

最佳答案

尝试这个实现:

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

关于java - hibernate : How to Join 3 tables in one join table by Annotation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38591170/

相关文章:

java - 来自 Java 的具有多级参数的 NuoDB 存储过程调用

java - 按类类型加载数据的通用 Spring Data JPA 存储库实现

java - 对于包含多个值并转换为数组的映射,正确的语法是什么

python - 来自 ManyToMany 关系的查询集

django - 在 Django 中使用 through 查询多对多字段

java - 如何在不实现 Serializable 接口(interface)的情况下序列化/反序列化对象?

java - 使用 Java 的 Docker : path RUN javac

java - 获取 "java.lang.NoClassDefFoundError: org/junit/platform/engine/DiscoverySelector"尝试运行 Serenity JBehave

java - hibernate 搜索 : Search any part of the field without losing field's content while indexing

python - 如何使用 related_name 查询 M2M