Hibernate merge not updating

JPA and Hibernate offer different options to initialize lazily fetched relationships.

My personal favorite is the @Named Entity Graph which provides a query independent way to define a graph of entities which will be fetched with the query.

As you can see, I use two independent Entity Managers and start a transaction with both of them, get the Author entity with id 1 and update the first name attribute.

hibernate merge not updating-4hibernate merge not updating-54hibernate merge not updating-57hibernate merge not updating-44

It fetches the Book relationship for an Author entity.

You can see an example for that in the following code snippet.

As you can see, I first call the get Entity Graph(String name) method on the Entity Manager to get an instance of the entity graph.

That should avoid most unnecessary Optimistic Lock Exceptions, and you’ll need to handle the rest of them in the client application.

But if only one user is causing the Optimistic Lock Exception on its own, you found a bug which you can easily fix.