Search code examples
javahibernatemany-to-manypersistence

hibernate does not insert to join table automatically


I'm working on a java spring mvc application with hibernate. I have two Entities Acl and AclGroupand These two entities have Many to Many relationship with a join table. But, when I save an AclGroup object, hibernate doesn't insert any record in join table and just inserts into AclGroup table. Here is structure of my classes:

Acl.java:

public class Acl implements Serializable{

    ...
    @JoinTable(name = "acl_group_acl", joinColumns = {
        @JoinColumn(name = "acl_id", referencedColumnName = "id")}, inverseJoinColumns = {
        @JoinColumn(name = "acl_group_id", referencedColumnName = "id")})
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Collection<AclGroup> aclGroupCollection;

    public Collection<AclGroup> getAclGroupCollection() {
         return aclGroupCollection;
    }


     public void setAclGroupCollection(Collection<AclGroup> aclGroupCollection) {
         this.aclGroupCollection = aclGroupCollection;
    }
 ...
}

AclGroup.java:

public class AclGroup implements Serializable{
  ...
      @ManyToMany(mappedBy = "aclGroupCollection",fetch = FetchType.LAZY)
      private Collection<Acl> aclCollection; 

      public Collection<Acl> getAclCollection() {
          return aclCollection;
      }


      public void setAclCollection(Collection<Acl> aclCollection) {
         this.aclCollection = aclCollection;
      }
}

Here is how I save my object:

AclGroup aclGroup = new AclGroup();
List<Acl> acls = new ArrayList<>();
/*
 add some elements to acls
*/
aclGroup.setAclCollection(acls);
/*
 hibernate config and opening a session
*/
session.save(aclGroup); //session.persist also did not work

Could anyone help me to solve this problem? Thank you for your attention.


Solution

  • The owner side of the association is Acl. AclGroup is the inverse side (since it has the mappedBy attribute). Hibernate only cares about the owner side.

    So make sure to add the group to the acl when you add the acl to the group: that will work whatever the owner side is, and will make your graph coherent. Or, if you absolutely don't want to do that, put the mapping annotations on AclGroup, and make Acl the inverse side.