views:

37

answers:

1
+3  A: 

It's the normal and default 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.

From 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.

From 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.

Rafael Belliard
Just to make sure I understand, setting the Session.FlushMode to FlushMode.Never then calling Session.Update will update only user1 in my example.
sh_kamalh
@sh_kamalh Although I'd prefer Evict(obj), take a loot at http://nhforge.org/doc/nh/en/index.html#manipulatingdata-flushing
Rafael Belliard