Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate merge and flush do not persist changes to an object

This is a Hibernate/JPA question around updating an object in the database.

I have an object that I created in another transaction using entityManager.persist(object).

This object is returned and then some values are updated. A call then is made in another method that is annotated with @Transactional. This method calls a merge method in a base class (shown below).

In the following code, rvalue has the modified information up until refresh is called. Once refresh is called, the data is back to the original values.

I would expect that the call to flush() would persist the information to the database.

I tried commenting out the refresh call, thinking the save does not happen until I leave the method wrapped in transactional. However, I am still finding the changes are not being persisted.

Any ideas on what may be happening would be greatly appreciated!

@Override
public T merge(T object) {
    T rvalue = entityManager.merge(object);
    entityManager.flush();
    entityManager.refresh(rvalue);
    return rvalue;
}
like image 373
Todd Patch Avatar asked Dec 19 '22 20:12

Todd Patch


1 Answers

I figured out what the problem was. It turns out the issue did not have to do with the entityManager or the @Transaction settings. It was the Entity. One of the fields I was trying to update was marked as updatable=false. Once I found and changed that parameter all was well. I am used to seeing this setting on the @Column annotation on the getter where it is defined, but found that it was overridden with an @AttributeOverride annotation in the derived class.

While this turned out to be an easy and uncomplicated reason and fix, the path to get there had its issues. In all my troubleshooting (stepping through code, turning up logs for Hibernate and Spring, etc...) I did not run into any exceptions that the update failed due to this constraint.

like image 117
Todd Patch Avatar answered Jan 05 '23 01:01

Todd Patch