JPA 2.1 added a list of nice features to the specification. One of them is the support for bulk update and delete operations in the Criteria API. We will have a look at the new CriteriaUpdate and CriteriaDelete classes in this article.
Don’t want to read? You can watch it here!
The CriteriaUpdate interface can be used to implement bulk update operations. But be careful, these operations are directly mapped to database update operations. Therefore the persistence context is not synchronized with the result and there is no optimistic locking of the involved entities. If you use optimistic locking, you need to update the version column as part of your update statement.
The following code shows a bulk update of the amount of multiple orders.
As you can see, the implementation is very similar to implementing a CriteriaQuery known from JPA2.0. The main differences are the usage of the CriteriaUpdate interface and the call of the update specific set method.
The usage of the CriteriaDelete interface for bulk delete operations is nearly the same as of the CriteriaUpdate interface. Like the CriteriaUpdate operations, the CriteriaDelete operations are directly mapped to database delete operations. Therefore the persistence context is not synchronized with the result of this operation.
The example of a CriteriaDelete operation looks similar to the usage of CriteriaQuery known from JPA2.0 and the CriteriaUpdate operation described above:
OK, I don’t think this needs any explanation …
The new CriteriaUpdate and CriteriaDelete interfaces add the missing bulk update and delete operations to the Criteria API. From my point of view this is a small but great enhancement that allows us to use the Criteria API in even more situations. I like it!
If you want to try it yourself, you can use any JPA 2.1 implementation like Hibernate or EclipseLink . You can find the source code of the examples in my github repo.
And don’t forget to download your New Features in JPA 2.1 cheat sheet.
And if you like to read more about the new JPA 2.1 features, make sure to have a look at my other articles …