1. In a transaction
Flush occurs by default (this is Hibernate specific and not defined by the specification) at the following points:
1. before query execution*
2. from javax.persistence.EntityTransaction.commit()*
3. when EntityManager.flush() is called*
(*) if a transaction is active
The SQL statements are issued in the following order
1. all entity insertions, in the same order the corresponding objects were saved using EntityManager.persist()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions, in the same order the corresponding objects were deleted using EntityManager.remove()
Exception: entity instances using application-assigned identifiers are inserted when they are saved.
Except when you explicitly flush(), there are no guarantees about when the entity manager executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.getResultList()/Query.getSingleResult() will never return stale data; nor will they return wrong data if executed in an active transaction.
It is possible to change the default behavior so that flush occurs less frequently. The FlushModeType for an entity manager defines two different modes: only flush at commit time or flush automatically using the explained routine unless flush() is called explicitly.
em = emf.createEntityManager();
Transaction tx = em.getTransaction().begin();
em.setFlushMode(FlushModeType.COMMIT); // allow queries to return stale state
Student izi = em.find(Student.class, id);
izi.setName(iznizi);
// might return stale data
em.createQuery("from Student as student left outer join student.kittens kitten").getResultList();
// change to izi is not flushed!
...
em.getTransaction().commit(); // flush occurs
During flush, an exception might happen ( if a DML operation violates a constraint). TODO: Add link to exception handling.
Hibernate provides more flush modes than the one described in the JPA specification. In particular FlushMode.MANUAL for long running conversation. Please refer to the Hibernate core reference documentation for more informations.
2. Outside a transaction
In an EXTENDED persistence context, all read only operations of the entity manager can be executed outside a transaction (find(), getReference(), refresh(), and read queries). Some modifications operations can be executed outside a transaction, but they are queued until the persistence context join a transaction. This is the case of persist(), merge(), remove(). Some operations cannot be called outside a transaction: flush(), lock(), and update/delete queries.