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 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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains dirty checking, generated SQL, flush timing, flush modes, and the transaction requirement.
Examples
Uses a changed Item name queried under FlushModeType.COMMIT and an ItemBidSummary subselect synchronized with two tables.
What it assumes
Assumes basic use of EntityManager, transactions, and queries while explaining how the persistence context detects changes.
What you can do after
Apply it via EntityManager.flush() during a transaction and configure query synchronization with FlushModeType or Hibernate @Synchronize.
How it connects
Connects the persistence context and dirty checking to transactions, queries, flush modes, 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.