I have a User class with the following:
Code:
@OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
UserProfile userProfile;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "auth_user_groups", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") })
private Set<Group> groups = new HashSet<Group>();
I can successfully load the user but much later in the program flow, I need to access the groups using user.getGroups(). Obviously the session that I used to load the user is no longer active.
So I thought I could open a new session and then get the groups, but I'm getting an exception:
Code:
session = SessionManager.getDAOFactory().openSessionForModel("User");
try {
tx = session.beginTransaction();
logger.debug("User groups: " + user.getGroups().toString());
....
Code:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: myapp.db.model.auth.User.groups, could not initialize proxy - no Session
I tried using initialize:
Code:
session = SessionManager.getDAOFactory().openSessionForModel("User");
try {
tx = session.beginTransaction();
Hibernate.initialize(user.getGroups());
....
But I'm getting a different exception:
Code:
org.hibernate.HibernateException: collection is not associated with any session
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:678)
I seem to be missing something in my understanding. Any suggestions appreciated.
Thanks