Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 461
lior Avatar asked Feb 05 '14 11:02

lior


1 Answers

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.

like image 68
Oliver Drotbohm Avatar answered Sep 25 '22 20:09

Oliver Drotbohm