Spring data JPA with H2 database not returning non-merged data

I have an entity with created_date (updateable = false) and updated_date fields. I have @PreUpdate method where I change the updated_date value only (not change created_date), and @PrePersist method which sets new created_date and updated_date values. On Persist the created_date and updated_date are rightly persisted and the returned entity has the correct values. When I pass in the entity to merge, it rightly updates the updated_date (@PreUpdate), and I don't pass the created_date in input. In the database the right updated_date value is updated and created_date value is not changed rightly. But the returned entity has the created_date value set to null. Any Ideas why? Shouldn't the merged entity return the full entity loaded from the database?



1 answer

  • answered 2018-04-17 05:19 Madhusudana Reddy Sunnapu

    I think that is inline with the JPA merge javadoc.

    Merge - Merges the state of the given entity into the current persistence context and returns the managed instance that the state was merged to.

    • (With hibernate as persistence provider) Merge starts with loading the data from the database for that entity, then copies detached entities state to the newly loaded entity. Subsequently, at a later point, during the transaction commit phase(or flush) the dirty checking mechanism fires the update query but won't include the fields marked as updatable=false.
    • So it doesn't attempt to reload the object with the data in the database after the UPDATE.

    To trigger reload, you can rely on refresh(...) that will reload the data.

    If it is spring-data-jpa it doesn't expose any refresh method, so you need to add it to your repository and and an example can be found here and discussion on this topic in the spring forum here.