I have a User table and a Group table. Their relation is a simple many-to-many one, since I am eventually interested in things like:
user.groups() // groups the user belongs to
group.users() // members of this group
I also have a UserDAO with basic methods (persist, update, etc). I would like to load a User and eventually let hibernate lazy-load their groups if needed. The problem is that the following does not work since the object is detached:
Code:
test:
User user = UserDAO.getUser("someone");
Set<Group> groups = user.getGroups(); --> does not work
UserDAO.java
public static User getUser(String username) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User aUser = (User)session.createQuery("from User user where user.userName= :userName")
.setParameter("userName", username)
.uniqueResult();
session.getTransaction().commit();
return aUser;
}
The documentation says that the call to getGroups() has to be before the session is closed. The problem is that I only know if I will need to load this information when I am in the business logic layer of my application, so I don't have direct access to hibernate sessions neither do I want to go back and deal with DB stuff once I've already used my DAO and loaded my object.
The alternative would be to turn lazy loading off but that is not a viable solution when I have lots of objects with lots of collections.
This is a basic issue so I'm guessing there must be a more solid solution to this. How is this usually solved?
Thanks.