liveBook · Manning

Unsynchronized persistence context

As explained in Java Persistence with Spring Data and Hibernate epub

An unsynchronized persistence context is a persistence context that is not automatically joined to an active transaction and therefore does not automatically flush changes.

An unsynchronized persistence context lets an EntityManager read data without automatically joining an active transaction or flushing changes. It queues in-memory modifications until the context joins a transaction, separating entity usage from transaction boundaries. section 11.0

Reading and Reverting Without a Transaction

EntityManager em = emf.createEntityManager(); Item item = em.find(Item.class, ITEM_ID); item.setName("New Name"); // Scalar query reads the database value: "Original Name" // Entity query returns the managed instance: "New Name" // em.flush(); // throws TransactionRequiredException em.refresh(item); // restores the current database state section 11.3.1

Operational behavior differs between database reads, managed entities, and write-oriented operations:

  • Executes find(), getReference(), refresh(), and queries as reads in database auto-commit mode. section 11.3.1
  • Avoids automatic flushes before queries, so scalar results can reflect the database while managed entities retain changed in-memory state. section 11.3.1
  • Rejects manual flushes, updates, and non-NONE locking with TransactionRequiredException. section 11.3.1
  • Restores an entity from the database with refresh(), overwriting unsaved changes in memory. section 11.3.1

Use this mode when reads must proceed outside explicit transactions but modifications should remain queued until transaction participation is deliberate. Transaction boundaries still provide stronger isolation and controlled rollback. section 11.5

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains reads, query flushing, managed identity, refresh, and transaction-required failures, but defers configuration mechanics.
Examples
Uses a changed Item name to contrast scalar queries, managed-entity queries, flush failure, and refresh-based restoration.
What it assumes
Assumes familiarity with EntityManager, managed entities, queries, transactions, and database auto-commit behavior.
What you can do after
Evaluate read and write behavior when using an EntityManager outside transactions.
How it connects
Connects persistence contexts with transactions, auto-commit mode, EntityManager operations, flushing, and pessimistic locking.

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.