views:

928

answers:

3

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.

+2  A: 

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.

Elie
Actually I have the object to the new session doing this, calling the get with the new session, but the point is trying to avoid calling the db again, because of performance improving purposes.
Victor Rodrigues
+2  A: 

Besides Evict + Lock you could make use of 2:nd level cache to reconstruct entities without going to the database. I don't know if it fits your application but I also think it's possible to pass the session to the other tread as long as the first thread stops making changes to it.

Cristian Libardo
+1  A: 

I detached it from the first thread, after attaching to the other thread.

Victor Rodrigues