我正在使用hibernate处理java spring mvc应用程序。我有两个实体Acl
和AclGroup
,这两个实体与连接表有多对多关系。但是,当我保存AclGroup
对象时,hibernate不会在连接表中插入任何记录,只需插入AclGroup
表。这是我班级的结构:
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
有人可以帮我解决这个问题吗?谢谢你的关注。
答案 0 :(得分:3)
该协会的所有者方是Acl。 AclGroup是反面(因为它具有mappedBy
属性)。 Hibernate只关心所有者方。
因此,当您将acl添加到组时,请确保将组添加到acl:无论所有者方是什么,它都将起作用,并使图形连贯。或者,如果您绝对不想这样做,请将映射注释放在AclGroup上,并使Acl成反面。