我正在尝试级联映射两个多对多关联。我有三个类:用户,用户组和权限。第一个与第二个有很多关联,而第二个与第三个有很多关联。

我正在使用休眠4.2.0

@Entity
@Table(name = "user")
public class User implements Serializable {
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = org.weedea.bidupsys.user.logic.model.UserGroup.class)
    @JoinTable(name = "UserGroupUser", joinColumns = { @JoinColumn(name = "userId") }, inverseJoinColumns = { @JoinColumn(name = "userGroupId") })
    private List<UserGroup> userGroupList = null;
}

@Entity
@Table(name = "userGroup")
public class UserGroup implements Serializable {
    @ManyToMany(fetch = FetchType.EAGER, targetEntity = org.weedea.bidupsys.user.logic.model.Permission.class, cascade = { CascadeType.ALL })
    @JoinTable(name = "UserGroupPermission", joinColumns = { @JoinColumn(name = "userGroupId") }, inverseJoinColumns = { @JoinColumn(name = "permissionId") })
    private List<Permission> permissionList = null;
}


使用这种配置,我会收到一个错误,因为我尝试同时加载两个渴望的集合:

javax.servlet.ServletException: cannot simultaneously fetch multiple bags
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:229)


如果将fetch = FetchType.LAZY放在第二个集合上,则会出现另一个错误:

failed to lazily initialize a collection of role: org.weedea.bidupsys.user.logic.model.UserGroup.permissionList, could not initialize proxy - no Session


如何将这两个多对多关联映射?感谢帮助!

最佳答案

简短的答案是您需要将它们映射为java.util.Set

这是一篇很好的博客文章,解释了这个问题:Hibernate Exception - Simultaneously Fetch Multiple Bags

09-15 22:19