I am using Spring JPARepository with hibernate and have one question on entity update. I am calling jparepository.save(entity) by passing a single entity but in the trace logs i can see update statements issued for other rows in the database also. Before calling save , i have a findAll and the value of some entities are getting changed. but i am passing only one entity for save , but still all the updated entities are getting saved. Can you please provide any info on this.
Asked
Active
Viewed 1,784 times
1 Answers
8
When you load entities from the database then this entities are "managed entities". If you change "managed entities" (and submit the transaction later) you do NOT need to save them explicit. (This is what "managed" mean.)
But Hibernate will not update the database immediately, instead it will wait until:
- you commit the transaction
- you invoke
EntityManager.flush
or - you execute some Database Query or Save via Hibernate! (when you bypass Hibernate and execute the query for example by plain JDBC/Spring JDBC Template, then you need to invoke
EntityManager.flush
first, if not you will may not see the not jet flushed data (https://stackoverflow.com/a/29825882/280244))
And this is what you observed:
- 1) you load some entities, so they become managed
- 2) you modify them, but hibernate still does not execute the sql updates
- 3) you query for some entity or save one entity, hibernate flush the changes