Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain an object for two nHibernate sessions?

I am building a multithreaded system that works like this:

While there are entities:

  1. Gets an entity from nHibernate (using the current session)

  2. Starts a new thread that will work with this entity*

When I start this new thread, it is required to have a new Session, because nHibernate is not thread-safe. I create it, but the entity retrieved before doesn't work for this session.

Today I'm resolving this situation retrieving from nHibernate a new Entity passing the id. But this is expensive, and I'm trying to save some time to achieve my SLA.

Is there any way for linking this object to this new session without needing to do a new database call? The other session will not be closed, they're all opened until the end of the application.

like image 902
Victor Rodrigues Avatar asked Nov 07 '08 16:11

Victor Rodrigues


1 Answers

If you're working with detached objects, you will have to reattach them to the session. You can do that if you have the correct Hibernate ids of the objects you're working with, calling a get, and then merging your copy with the one Hibernate just put into session. Make sure you use merge, though, because saveOrUpdate() will not delete any children that are missing from the detached object, just add the new children and save changes to existing children.

like image 126
Elie Avatar answered Oct 27 '22 14:10

Elie