Why does hibernate do a select before saving an object?
I can't find useful information on internet. Is this normal behavior before every save? I found this topic, select Query Run for hibernateTemplate.save() - save, but I do not find this answer "definitive". I mean, do we have to use versioning if i want to avoid this select before saving each object?
I would appreciate all the explanations or links.
Hibernate save method returns the generated id immediately, this is possible because primary object is saved as soon as save method is invoked. If there are other objects mapped from the primary object, they gets saved at the time of committing transaction or when we flush the session.
The save() method INSERTs an object in the database. It will persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created. The saveOrUpdate() calls either save() or update() on the basis of identifier exists or not.
The mechanism Hibernate use to generate query is call dirty checking. By default once you load an record from the database Hibernate will store a snapshot of the entity in the persistence context and give you a managed entity.
The main intention of the merge method is to update a persistent entity instance with new field values from a detached entity instance.
So Julia is right, calling Session.save()
with an entity that has its IDs assigned results in hibernate doing a SELECT
and then an INSERT
. Fortunately there are two workarounds:
Session.persist()
rather than Session.save()
The second option also works seamlessly with Envers.
Hope this saves someone else hours of hunting.
I know you have answered your own question in the question's comment, but just to summarise this here are some general points.
Just to clarify, NHibernate uses 'save' as in 'SQL INSERT' and 'update' as in 'SQL UPDATE'.
I know of these common scenarios when NHibernate will fetch an object implicitly (no explicit use of s.Update) from the db before persisting it:
As with your example, this may not be obvious when parent-child objects are used (but simple rules stay the same) as it may not be obvious from the code that children will be fetched.
No, it doesn't do a select before a save. Are you sure your edit-save usecase is right? A common flow for webapps is:
A single sql update will be executed which also handles versioning. If the version number is out of sync, a StaleObjectStateException
will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With