liveBook · Manning

Flush

As explained in Java Persistence with Spring Data and Hibernate epub

A flush is the persistence operation that synchronizes pending in-memory entity changes with the database before an operation that may depend on those changes.

A flush synchronizes pending changes in a persistence context with the database. The provider detects changes to managed entities through dirty checking and executes the necessary SQL INSERT, UPDATE, or DELETE statements. Synchronization can happen automatically or on demand. section 10.1.2

Hibernate normally flushes when a joined transaction commits, and it may flush before a query so that the query can see earlier changes. During an active transaction, call EntityManager.flush() to force dirty checking and synchronization explicitly. Flushing is not the same operation as committing: it can occur before a query while the transaction is still in progress. section 10.2.9 section 10.2.1

Flush mode controls the usual query-time behavior:

  • FlushModeType.AUTO is the default when the EntityManager joins a transaction. Hibernate normally synchronizes relevant in-memory changes before a query. section 10.2.9
  • FlushModeType.COMMIT disables flushing before queries; synchronization occurs at commit. A query can therefore return a database value that differs from the in-memory value. 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 is changed in memory, but the scalar query returns the original database value under COMMIT mode. The transaction commit then flushes the change. section 10.2.9

For a modified Item, Hibernate compares the managed instance with a snapshot taken when it was loaded. At flush, a difference requires an UPDATE. Snapshot storage consumes memory, and comparing instances with their snapshots can make dirty checking time-consuming. Deferring DML toward transaction completion also helps keep database lock duration short. section 10.2.3

A read-only entity mapped to a Hibernate subselect needs special attention: without a mapped table, Hibernate may not know which pending changes affect its query. List the tables referenced by the SELECT in @Synchronize so Hibernate knows to flush relevant changes before querying the entity; otherwise results may be stale. 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 summary query reads ITEM and BID, and @Synchronize names both tables for query-time flushing. section 5.3.4

Without an active transaction, the persistence context is unsynchronized and Hibernate does not automatically flush. A scalar query can return the original database value while an entity query returns the already-managed instance with its changed value. Calling flush() in this state throws TransactionRequiredException; refresh() instead reloads database state and overwrites the in-memory change. section 11.3.1

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains dirty checking, SQL synchronization, flush modes, transaction requirements, and subselect synchronization, including snapshot and locking implications.
Examples
Uses an item-name update and scalar query to compare flush modes, plus an item-and-bid summary mapped to a subselect.
What you can do after
Operate/configure flushing with EntityManager.flush(), FlushModeType, and Hibernate @Synchronize, and recognize when query results may be stale.
How it connects
Connects flush to persistence contexts, dirty checking, transactions, query results, and subselect mappings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.