liveBook · Manning

Persist

As explained in Java Persistence with Spring Data and Hibernate epub

persist is the EntityManager operation that makes an entity instance persistent and can cancel a pending removal before synchronization.

`EntityManager.persist()` moves a new entity instance from transient to persistent state. The instance becomes managed by the current persistence context and is scheduled to have a database representation. Calling `persist()` does not necessarily execute an SQL `INSERT` immediately. section 10.1.1 section 10.2.2

Save a new entity

Create and initialize an entity, then make it persistent: Item item = new Item(); item.setName("Some Item"); em.persist(item); Long itemId = item.getId(); Hibernate normally flushes the context and executes the `INSERT` when the transaction commits; it may batch that statement with others. An identifier generator that requires an insert can instead cause the `INSERT` during `persist()`. Do not assume the identifier is available before flushing in every configuration. section 10.2.2

The same operation has two other useful roles:

  • Undo a pending removal: call `persist()` on a removed instance before the persistence context is flushed to make it persistent again and cancel its deletion. section 10.2.5
  • Persist through an association: with `CascadeType.PERSIST` enabled, adding new billing details to an already-persistent user makes the added instances persistent. section 10.1.1 section 13.1.3

With an unsynchronized persistence context and a pre-insert identifier generator, `persist()` can assign an identifier while leaving the `INSERT` queued. Join the context to a transaction when ready to write; synchronization and flushing occur at commit. section 11.3.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Works through entity-state changes, identifier timing, flushing, and queued writes; does not detail identifier-generator strategies.
Examples
Uses a new `Item`, an undoable removal, and billing details added through a persistent user’s collection.
What it assumes
Assumes Java entity instances and EntityManager use while defining transient and persistent states.
What you can do after
Apply it via `EntityManager.persist()` to save new entities and reverse a pending removal before flushing.
How it connects
Links persistence contexts, transactions, flushing, identifier generation, removal, and cascade persistence.

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.