How to update the @Version field when executing a bulk update through Spring Data JPA

jpa, jpa-2.0, spring-data, spring-data-jpa, version

Solution

Section 4.10 of the JPA 2.0 specification explicitly states:

Bulk update maps directly to a database update operation, bypassing optimistic locking checks. Portable applications must manually update the value of the version column, if desired, and/or manually validate the value of the version column.

Generally speaking bulk updates and deletes pretty much bypass a lot of functionality that is applied by the persistence provider that you might be used to when simply saving an entity. Besides optimistic locking this includes the persistence provider managed cascading of persistence operations.

Problem

I'm using spring data repositories and I have a problem I cant find the answer. My repository query is: ``` @Modifying @Query("UPDATE User u SET u.firstName = 'blabla' WHERE u.loginName = 'admin'") public int test(); ``` And the entity `User` has an `javax.persistence.Version` annotated field: ``` @Version private Long version; ``` When I execute the query the version field doesn't updates, but if instead of the query i do: ``` User user = this.userRepository.findUserById(1L); user.setFirstName("blabla"); this.userRepository.save(user); ``` the version field is updated. Why?

Original source