gpt4 book ai didi

nhibernate - 为什么当我从不执行session.Save时,NHibernate为什么保存对象?

转载 作者:行者123 更新时间:2023-12-04 05:21:16 26 4
gpt4 key购买 nike

我正在使用NHibernate和Fluent NHibernate。

我有启动交易的代码,然后进入创建多个对象的循环。对于每个对象,我都会检查某些条件。如果满足这些条件,则对对象执行session.SaveOrUpdate()。在循环结束时,我发出了一个提交事务。

我在session.SaveOrUpdate命令上设置了一个断点,证明它从未达到(从未达到)(因为循环中的任何对象均未满足条件)。但是,在提交事务时,将保存对象!

我正在使用AuditInterceptor,并在OnSave方法中设置了一个断点。它被调用,但是堆栈跟踪仅追溯到提交事务的语句。

目前,尚无任何对象执行过SaveOrUpdate,因此级联并不能解释它。

NHibernate为什么要保存这些对象?

最佳答案

NHibernate ISession.Update线程:

这是normaldefault behavior:

Hibernate maintains a cache of Objects that have been inserted, updated or deleted. It also maintains a cache of Objects that have been queried from the database. These Objects are referred to as persistent Objects as long as the EntityManager that was used to fetch them is still active. What this means is that any changes to these Objects within the bounds of a transaction are automatically persisted when the transaction is committed. These updates are implicit within the boundary of the transaction and you don’t have to explicitly call any method to persist the values.



Hibernate Pitfalls part 2:

Q) Do I still have to do Save and Update inside transactions?

Save() is only needed for objects that are not persistent (such as new objects). You can use Update to bring an object that has been evicted back into a session.



来自 NHibernate's automatic (dirty checking) update behaviour :

I've just discovered that if I get an object from an NHibernate session and change a property on object, NHibernate will automatically update the object on commit without me calling Session.Update(myObj)!

Answer: You can set Session.FlushMode to FlushMode.Never. This will make your operations explicit ie: on tx.Commit() or session.Flush(). Of course this will still update the database upon commit/flush. If you do not want this behavior, then call session.Evict(yourObj) and it will then become transient and NHibernate will not issue any db commands for it.

关于nhibernate - 为什么当我从不执行session.Save时,NHibernate为什么保存对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5348152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com