Question

Can I use JPA @Version with Spring Data REST?

In Spring Data REST 1.1.0.M1 I can configure the repo exporter to expose the entity ID, which as it happens also exposes @Version-annotated fields. So I thought that if I tried to PUT an entity with some old version number, I'd get the OptimisticLockException. But that doesn't occur. Instead the PUT succeeds (including data updates), except that the version number is always strictly incremented instead of being whatever old version I set it to.

I read here that I'm not supposed to set the version number myself, since the behavior is undefined. That makes sense. But it seems that this makes @Version useless in cases where all I have is the JSON representation of an entity instead of having a reference to the entity: with the JSON representation I'd need to send the version number back to the service, which would eventually call setVersion(), which in turn leads to undefined behavior.

Am I understanding the situation correctly? Can I use @Version with Spring Data REST?

UPDATE: Given Marten's response, I ended up using JPA events to achieve the optimistic locking capability. I wrote up the approach here:

http://springinpractice.com/2013/09/14/optimistic-locking-with-spring-data-rest/

Was it helpful?

Solution

I would say no, and that has not much to do with the use of Spring Data REST. You already mention you cannot set the version yourself as what happens then is undefined (I had this pleasant experience myself also). You basically have the same issue when posting normal form data and not storing the current version in the session (@SessionAttributes).

What we ended up doing was that we wrote a hibernate interceptor (would be a listener now I guess) which does the checking (so that we could actually set the version field). This worked without to much problems (but that was about 6 years ago), so Hibernate might have changed and could be acting differently now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top