liveBook · Manning

Transient state

As explained in Java Persistence with Spring Data and Hibernate epub

A transient entity is a newly created entity instance that is not yet associated with persistent storage and has no database identifier.

A newly created entity, such as `new Item()`, is transient: it is not managed by a persistence context and has no database representation. Changes to it are ordinary Java object changes; Hibernate cannot roll them back. If nothing references the object, it can be garbage-collected. section 10.1.1

Saving a new entity

`Item item = new Item(); item.setName("Some Item"); em.persist(item);` The `persist()` call moves the instance into persistent state and associates it with the current persistence context. Hibernate issues an SQL `INSERT`, normally when the context flushes at transaction commit, though an identifier strategy can require an immediate insert. section 10.2.2

An enabled cascade can also make a transient entity persistent when an already-persistent entity begins referencing it. Alternatively, `merge()` accepts a transient entity, copies its values into a new persistent instance, and returns that instance. Keep the returned reference: the original object does not become the managed result. section 10.1.1 section 10.3.4

A null value from `PersistenceUnitUtil#getIdentifier(entity)` can indicate transient state, but identifier checks need care: assignment may wait until flush, and Hibernate does not return null for a primitive identifier. Do not confuse a new transient entity with a removed one. `remove()` first puts a managed entity in removed state and queues its database deletion; Hibernate may leave its old identifier in place afterward. section 10.2.2 section 10.2.5

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains creation, state transitions, identifier checks, and insert timing without detailing identifier-generator strategies.
Examples
Creates an `Item`, sets its name, and calls `EntityManager.persist()` to make it persistent.
What it assumes
Assumes familiarity with Java object creation and introduces the JPA entity-state transitions needed to manage those objects.
What you can do after
Apply it via JPA `EntityManager.persist()` or `merge()` to store new entities while handling managed references correctly.
How it connects
Connects transient state to persistent, detached, and removed states, persistence contexts, cascading, and merging.

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.