Search code examples
javahibernatehibernate-mapping

How to resolve many-to-many relationship without creating a junction class in Java?


In my DB I have three table USER, PERMISSION and a junction table USER_PERMISSIONS. As you can see I have clear many-to-many relationship.

And here is the question. I'm using a Hibernate. Is it possible to use only two classes, User and Permissions without creating a junction class UserPermissions? I mean can I use some kind of annotations to include my junction table USER_PERMISSIONS?


Solution

  • Yes you can. You need to use the @JoinTable and @JoinColumn annotation. Example below:

    @Entity
    @Table(name = "USER")
    public class User {
    
    @Id
    @Column(name = "ID")
    private Long id;
    
    @ManyToMany
    @JoinTable(name = "USER_PERMISSIONS", 
        joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), 
        inverseJoinColumns = @JoinColumn(name = "PERM_ID", referencedColumnName = "ID"))
    private Collection<Permissions> permissions;
    

    A full working example with bidirectionaly many to many can be found in here http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany