puks7 wrote:
sebbo wrote:
IMHO you have to reattach every single object in the collection using Session#update() or Session#lock().
This is only true for the collections you get by querying your session (like in your case) because the collection (List) returned by Session#list() is not a persistent object but only a collection of persistent objects.
Yea I had tried this a couple of days back, but then it really gets hard to keep track of which object in which list is associated with which session. (assume you had to do this for a couple of lists and they had common persistent objects).
so for now I ve decided to pass the session via which i obtained the list so sessions could be well organized/maintained. i doesnt sound like the best way to do this, so if any of you can suggest a better way to handle a situation like this, i would be very greatfull :)
You don't need to know which session a detached object was originally loaded with. You can reattach it to a new session. That's the trick with reattaching!
Code:
Session s1 = ...; // get session from somewhere and begin transaction
List list = s1.createQuery(...).list();
s1.close(); // also commit transaction here
// all objects in list are detached from s1
// the following could happen somewhere in your code
Session s2 = ...; // get another session and begin another transaction
for(Object o : list) {
s2.update(o); // o is reattached to s2.
// there are some other other methods to reattach like lock()
// and merge. Consult the docu
}
// do some work like accessing lazily fetched collections, changing the
// objects, ...
s2.close(); // also commit transaction here
// all objects in list are detached from s2
If you just want to initialize a lazily fetched collection of a detached object, do the following:
Code:
ObjectWithCollection o = ...;
Session s = ...; // get session from somewhere and begin transaction
s.update(o);
Hibernate.initialize(o.getLazyCollection());
s.close(); // also commit transaction here
Regards
Sebastian