Search code examples
javahibernateormjpaentity-relationship

Create ORMapping using OneToMany relations for 3 tables


I have 3 tables: Project, User and Role. Now I would like to have a table Project2User2Role with the embedded key id_project, id_user,.

I tried it using @OneToMany relations in all three entities but I think I cannot build it like that.

And I also tried to build a Project2User2Role entity class by my self but than I have to make an idclass without the @ManyToOne relations.

How could the solution look like?


Solution

  • The reference manual says that you can embed a relationship inside an embedded ID :

    While not supported in JPA, Hibernate lets you place your association directly in the embedded id component

    You should thus define a Project2User2Role entity with an ID of type Project2User2RoleId:

    @Entity
    public class Project2User2Role {
        @EmbeddedId
        private Project2User2RoleId id;
    
        public User getUser() {
            return this.id.getUser();
        }
    
        public Project getProject() {
            return this.id.getProject();
        }
    
        // ...
    }
    

    The Project2User2RoleId class would look like this :

    @Embeddable 
    public class Project2User2RoleId {
        @ManyToOne(optional = false)
        @JoinColumn(name = "project_id")
        private Project project;
    
        @ManyToOne(optional = false)
        @JoinColumn(name = "user_id")
        private User user;
    
        @ManyToOne(optional = false)
        @JoinColumn(name = "role_id")
        private Role role;
    
        // constructor
        // getters
        // equals and hashCode
    }