Search code examples
hibernatejpamany-to-manyhibernate-mapping

JPA,RELATIONSHIP BEGINEER MANY TO MANY with some complexity


I have 4 Entities in My domain model which is an Professor College Department and Role. The use case are

  1. Professor can only work for one college which makes One to Many Relation ship (College -> Professor)
  2. Professor will have a Many Roles at college level (Admin, Food Inspector ??)
  3. Professor can work for many departments (Many to Many)
  4. In each department professor may have a different role

    class Professor {
        @ManyToOne
        private College workingWithCollege;
        @JoinTable(name = "professor_college_role",
                   joinColumns = @JoinColumn(name = "professor_id"),
                   inverseJoinColumns = @JoinColumn(name = "role_id"))
        @OneToMany
        private Collection<Role> roles;
     }
    
    class College {
    
    }
    
    
    class Department {
    
    }
    
    class DepartMentRole {
        @ManyToOne
        private Department department;
        @ManyToOne
        private Role role;
        //TODO: Dont know how exactly to solve this
    }
    
    class ProfessorDepartmentRole {
         @OneToOne
         private Professor professor;
         @OneToMany
         private Collection DepartmentRole;
    }
    

DO we really need Department Role how to connect a professor to a department and a role for that department


Solution

  • I would convert the ProfessorDepartmentRole class to a Many to Many (as suggested by KLibby). So to answer your question, we do retain the DepartmentRole class. Also, then you can remove the collection roles from Professor class since you can derive the roles via the 2 join tables.