Quote:
I have to reattach the User object from the HTTPSession to the Hibernate Session in order to traverse the object graph (getting myFacilities). I have 2 choices: 1. use Session.lock or 2. use Session.update. In both cases I am getting bad behavior.
This didn't make sense to me at first, but now it is clear: you're loading a User in one session whithout it's associations, and you're trying reuse the same user instance in another session but you want to load the associated data? However, you are
not trying to update the User. Please correct me if I am mistaken.
Reattaching persistent objects to a new session that were loaded in a previous Session is a fully supported feature of Hibernate. However, this feature is generally used for update oprtations, not a "read-more" data operations. I too am grappling with a similar situation where I have a business operation that uses the same data in once transaction and passes it off to another transaction which loads up the same data, plus additional data that would be used for presentaion. Ideally, we'd like to reuse the same instance from transaction 1, but since there is is no good way to achieve this, we have to reload the data.
The two Session methods you have tried will get you into trouble if you are
not trying to update the User & Chemicals. I have looked at Session.merge() and Session.load(Object,id) (both of which are vaguely documented in the Java Docs) and merge is the only one which would "kinda" do what you want. However, it does function somewhat like update and you will most lilkely get the issue you have in case2.
One way around this is to utilize the second-level cache and reload the User instance. So you could do something like this:
Code:
/*
* Reloads the user, but will get it from the L2 cache
*/
User user = (User) session.load(User.class,user.getId());
/*
* Load the chemicals from the database if not already in the cache
*/
List chemicals = user.getChemicals();
This will avoid a database hit but achieve the same goal. Another option would be load the user with the data that you will need up front.
But I agree, it could be useful to simply be able to reattach an instance to another session without the intent for an Update.
Ryan-
P.S. don't forget to rate :)