我正在使用hibernate开发Java Spring MVC应用程序。我有两个实体AclAclGroup,这两个实体与一个联接表具有多对多关系。但是,当我保存AclGroup对象时,hibernate不会在连接表中插入任何记录,而只是插入到AclGroup表中。这是我的 class 结构:

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

这是我保存对象的方式:
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

谁能帮我解决这个问题?感谢您的关注。

最佳答案

关联的所有者是Acl。 AclGroup是反面的(因为它具有mappedBy属性)。 Hibernate只关心所有者方面。

因此,在将ACL添加到组时,请确保将组添加到ACL:无论所有者侧是什么,它都将起作用,并使图保持一致。或者,如果您绝对不想这样做,则将映射注释放在AclGroup上,并使Acl相反。

10-05 17:47