I need some advice on how to keep objects in the session when working with
long sessions (as described in Hibernate in Action p. 325 8.2)
I would like to keep some object always bound to the current session, like for example, the user context object, after logging in to the system. This is very convenient, as the user object is always used somehow in the views.
So I always want to keep the user object around. This works smoothly until I want to start a application transaction, for example when I want to create a new user.
When I need to update an object or create new objects, I start a new application transaction, as shown in the book, and the session is cleared.
request 1: HibernateUtil.newApplicationTx();
..
request n: HibernateUtil.commitApplicationTx();
After that requests, accessing the user object sometimes works, sometimes not. Currently, the only safe way I found is to reload the object in each request, like this:
Code:
UserDAO userDAO = new UserDAO();
User user = userContext.getUser(); // get from http session
user = userDAO.getUserById(user.getId(), false);
I also tried this:
Code:
UserDAO userDAO = new UserDAO();
User user = userContext.getUser();
userDAO.lock(user);
This seems to work, but sometimes I get a lazy-Exception.
So my question: What is the correct way? Always reload the objects in every request?
Thanks in advance,
Axel