开发者

NHibernate FlushMode: How do I set up NHibernate for automatically updating an entity

After I retrieve an entity, I change a property of it. Then I retrieve the same entity.

How do I say Nhibernate, that it shall update the entity before it loads the entity?

Here the code:

EmployeeRepository employeeRepository = new EmployeeRepository();
Employee employee = employeeRepository.GetById(4);
employee.LastName = "TEST!!!";
Employee employee2 = employeeRepository.GetById(4);

Currently Nhibernate don't make an update in my program. I thought just setting the FlushMode to Auto will update the entity automatically.

EDIT The background is that I try to reprdouce this behaviour in another application. There is NO save method! Just this code. The NHibernate version is really old, it is version 1.2.1.4000. maybe there is the catch.

When I set the FlushMode in the brownfield application to Commit then no update statement is generated.

But in my own project I still开发者_JS百科 can not reproduce this "automatic" behaviour.


Are both calls to the employeeRepository ultimately using the same NHibernate ISession instance? If so, then they will return the same object, and the updated LastName value will be reflected. If not, then you will need to make sure you are disposing your ISession instance each time to take advantage of auto flushing.


According to the documentation for the default FlushMode of Auto:

The ISession is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.

So you have to manually flush the session to ensure that your changes are persisted before reading the object again.

EmployeeRepository employeeRepository = new EmployeeRepository();
Employee employee = employeeRepository.GetById(4);
employee.LastName = "TEST!!!";
session.Flush();
Employee employee2 = employeeRepository.GetById(4);

If your repository is using the same ISession for both calls (as it should imo) then employee 4 will be retrieved from the cache and have the change. However, the change will not have been persisted to the database yet.

If your repository GetById methods uses a new session for each call then it will always hit the database to retrieve the employee. If you're disposing of the session in the method then your objects are returned as detached from a session. This strategy defeats the purpose of NHibernate and relegates it to a simple data access tool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜