如何为两个nHibernate会话维护一个对象?

问题描述:

我正在构建一个像这样的多线程系统:

I am building a multithreaded system that works like this:

虽然有实体:

  1. 从nHibernate获取一个实体(使用当前会话)

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

启动将与此实体配合使用的新线程*

Starts a new thread that will work with this entity*

当我启动这个新线程时,因为nHibernate不是线程安全的,所以需要有一个新的Session.我创建了它,但是之前检索到的实体在此会话中不起作用.

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.

今天,我正在解决从nHibernate检索通过id的新Entity的情况.但这很昂贵,我正在努力节省一些时间来实现我的SLA.

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.

如果要使用分离的对象,则必须将它们重新附加到会话中.如果您具有正在使用的对象的正确的Hibernate ID,则可以执行此操作,调用get,然后将您的副本与刚刚加入会话的一个Hibernate合并.但是,请确保使用合并,因为saveOrUpdate()不会删除分离对象中缺少的任何子项,而只需添加新的子项并将更改保存到现有子项中即可.

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.