Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
Hibernate always updates all database columns mapped by my entity, even the ones that I didn’t change. How can I tell Hibernate to exclude unmodified attributes from the update statement?
Don’t want to read? You can watch it here!
Generating SQL statements takes time and Hibernate, therefore, uses one cached SQL UPDATE statement per entity. It sets all database columns so that it can be used for all update operations. You can change that with the @DynamicUpdate annotation. It tells Hibernate to generate a new SQL statement for each update operation.
You can see an example of it in the following code snippet. The only thing you need to do is to add the @DynamicUpdate annotation to your entity class.
When you now modify the price of the Book entity, Hibernate generates an SQL statement for this operation. As you can see in the log messages, it only changes the price and version column in the Book table.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
You can also implement your own update statement with JPQL or the Criteria API. That allows you to customize the statement in any way you want. But please be aware, that Hibernate isn’t aware of the changes and doesn’t update its caches.
You can read more about custom update operations in:
- How to use native queries to perform bulk updates
- Criteria Update/Delete – The easy way to implement bulk operations in JPA 2.1
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.