简体   繁体   中英

Hibernate - multiple many to many associations - cannot simultaneously fetch multiple bags

I'm trying to map two many to many associations in cascade. I have three classes: User, Usergroup and Permission. The first one has a many to many association to the second one while the second one has a many to many association to the third one.

I'm using hibernate 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;
}

With this configuration I get an error, because I try to load simultaneously two eager collections:

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

If I put fetch = FetchType.LAZY on the second collection, I get another error:

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

How could I map this two many to many associations? Thanks for help!

Short answer is you need to map them as java.util.Set s.

Here's a nice blog post explaining the issue: Hibernate Exception - Simultaneously Fetch Multiple Bags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM