A flush synchronizes changes held in an EntityManager’s persistence context with the database. Hibernate detects modified managed entities and executes the necessary SQL INSERT, UPDATE, or DELETE statements. Flushing can happen before a transaction ends; it is not itself a commit. section 10.1.2 section 10.2.9
Hibernate can flush:
- When a joined transaction commits. section 10.2.9
- Before a query when pending changes may affect its result under the default AUTO flush mode. section 10.2.9
- When code calls EntityManager.flush() during a transaction. section 10.2.9
Changing an item
After `Item item = em.find(Item.class, id); item.setName("New Name");`, the changed name remains in the managed instance. A flush performs dirty checking and sends an SQL UPDATE. Hibernate normally delays that work toward transaction commit, reducing the time database locks are held. section 10.2.3
FlushModeType.COMMIT postpones synchronization until commit instead of flushing before queries. A scalar query can therefore return the old database value while a managed entity holds the new value. Use EntityManager.flush() within the transaction if the query must see the pending change. section 10.2.9
Path: managing-data/src/test/java/com/manning/javapersistence/ch10 /SimpleTransitionsTest.java – flushModeType() em.getTransaction().begin(); Item item = em.find(Item.class, ITEM_ID); item.setName("New Name"); em.setFlushMode(FlushModeType.COMMIT); assertEquals( "Original Name", em.createQuery("select i.name from Item i where i.id = :id", String.class) .setParameter("id", ITEM_ID).getSingleResult() ); em.getTransaction().commit(); // Flush! em.close();
The Item-name test shows a scalar query returning “Original Name” under FlushModeType.COMMIT, followed by a flush at commit. section 10.2.9
Query synchronization needs particular care for an entity mapped to a SQL subselect. Because the mapping has no table annotation, @Synchronize names the tables whose pending changes must be flushed before querying it. A subselect over ITEM and BID lists both tables to avoid a stale summary. section 5.3.4
Path: Ch05/subselect/src/main/java/com/manning/javapersistence/ch05/model /ItemBidSummary.java @Entity @org.hibernate.annotations.Immutable @org.hibernate.annotations.Subselect( value = "select i.ID as ITEMID, i.NAME as NAME, " + "count(b.ID) as NUMBEROFBIDS " + "from ITEM i left outer join BID b on i.ID = b.ITEM_ID " + "group by i.ID, i.NAME" ) @org.hibernate.annotations.Synchronize({"ITEM", "BID"}) public class ItemBidSummary { @Id private Long itemId; private String name; private long numberOfBids; public ItemBidSummary() { } // Getter methods . . . // . . . }
The read-only ItemBidSummary mapping combines @Subselect with @Synchronize({"ITEM", "BID"}). section 5.3.4
Do not treat flush as an option for writing outside a transaction. In an unsynchronized persistence context, Hibernate does not auto-flush, and a manual flush throws TransactionRequiredException. section 11.3.1
