JPA Versioning – The Right Way

You are probably messing your entity versioning mechanism right now, and you even don’t know why!

I am sure that you’re more than aware about @Version annotation and this whole mechanism in JPA. This works wonder when it comes to entity versioning, right?

But … are you sure?

Our example

Let’s say that you have some Person entity, and PersonDTO class for REST/Frontend purposes. Just like that :



As simple as it can get. We also have two simple REST operations.

  • GET – /person/{id}
    • find Person with given id in database
    • transform entity to DTO
    • send response with found DTO
  • POST – /person/{id} (with DTO in request body)
    • find Person with given id
    • copy all fields from DTO to Entity (except version)
    • save updated entity

If you know what is wrong with this scenario, that I won’t tell you anything new.

On the other hand if this sounds to you like a natural or even obvious solution, please bare with me : )

Critical use case

Let say we have a Person with version 0 in our database.

  1. Client A opens a form to change this Person information (GET)
  2. Client B opens a form to change this Person information (GET)
  3. Client A changes name to “Keanu” and saves the form (POST)
  4. Client B changes name to “Neo” and saves the form with no error (POST)

Now this Person has version = 2 and name = Neo !!! 😦

Client B overwrote Client A changes without even knowing that.

Informations were lost.

How does it happen? We wanted to situations like that end up with an error!

Isn’t that why we used Versioning mechanism? Does it work?


Yes, it works like inteded.

JPA provider has no idea that your data was stale, version is ok, it is read from a database. It only cares about managed entities and theris versions.

‘Some curoius programmer’ : So, why don’t we just change the version manually from DTO on entity to receive exception?

Providers like hibernate are using version read from a database, and not from entity you pass them. More information HERE


When you are aware of the problem, solution occurs naturally. Let’s compare version from DTO and entity. It we have mismatch, we throw an exception.

carbon (1)

Whenever you receive DTO from REST to save it in your database. Always, always, always check its version against the entity one.

Now you can double check for this data lose in your application, and come as The Data Savior in front of colleagues. 😀

Brain Daddy

One thought on “JPA Versioning – The Right Way

Add yours

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: