Some confusing explanation: flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into
In theory, you (as a user of JPA) should never (or in absolutely rare situations) get in a situation to call flush()
.
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory
In other words, on a flush()
all the insert, update, delete or whatever statements are actually called on the database, before a flush()
nothing happens on your database. Flushing is caused by a commit of your transaction or some kinds of database reads. For example if you execute a JPQL query, a flush()
has to be done to get the correct results from the database. But this is just very nice to know and completely handled by your JPA implementation.
There may be some situations you want to control this flushing on your own and then you can invoke it with flush()
.
Edit to answer the questions in comment:
Not on every read a flush is necessary, consider this scenario (one transaction):
Person p = em.find(Person.class, 234)
p.setAge(31)
Building b = em.find(Building.class, 123
select b from Building b where b.id = 123
Automatic flush occurs only before 4., because Eclipselink can't determine what you are gonna read, so the person's age must be up to date on the database before this read can occur. Before 3. there is no flush needed because Eclipselink knows that the update on a person can not affect a building.
To work with optimistic locking, you have to implement it. Read about the @Version
annotation here: https://blogs.oracle.com/carolmcdonald/entry/jpa_2_0_concurrency_and. Without that your entity will not use optimistic locking and the "last update wins".
When the transaction commits the entity manager does that flush-ing for you. In some case, like handling optimistic locking in a container-managed transaction, you may need to manually invoke the flush method to catch and handle specific locking exception.