简体   繁体   English

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

[英]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) 从nHibernate获取实体(使用当前会话)

  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. 当我启动这个新线程时,需要有一个新的Session,因为nHibernate不是线程安全的。 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. 今天我正在解决这种情况,从nHibernate中检索一个传递id的新实体。 But this is expensive, and I'm trying to save some time to achieve my SLA. 但这很昂贵,我正在努力节省一些时间来实现我的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. 另一个会话将不会关闭,它们全部打开,直到应用程序结束。

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. 如果您拥有正在使用的对象的正确Hibernate ID,调用get,然后将您的副本与刚刚进入会话的Hibernate合并,则可以执行此操作。 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. 但是,请确保使用merge,因为saveOrUpdate()不会删除分离对象中缺少的任何子项,只需添加新子项并将更改保存到现有子项。

Besides Evict + Lock you could make use of 2:nd level cache to reconstruct entities without going to the database. 除了Evict + Lock之外,您还可以使用2:nd级缓存来重建实体而无需进入数据库。 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. 我不知道它是否适合您的应用程序,但我也认为只要第一个线程停止对其进行更改,就可以将会话传递给另一个步骤。

在连接到另一个线程后,我将它从第一个线程中分离出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM