Card 06/ 07

ExerciseDifficulty: Advanced1 min

Practice: Naming an Entity's State After Each Line

Four lines of code, four states to name, and one change that goes nowhere.

An entity's state (transient, managed, detached or removed) changes with each EntityManager operation (the JPA calls that persist, detach, merge and remove entities). Managed means JPA is tracking it and saves its changes; detached means it is no longer tracked. Trace the sequence below and write down the state of t after each line, and whether line (d) reaches the database, before you open the answers.

java
Ticket t = new Ticket("open");        // (a)
em.persist(t);                        // (b)
em.detach(t);                         // (c)
t.status = "escalated";               // (d)
See the answers

(a) Transient. It has just been created, and nothing knows about it. (b) Managed. The persistence context is now tracking it. (c) Detached. The tracking has stopped, whether or not its row has been inserted yet. (d) Still detached. The field changes in memory, but nothing is watching, so the change never reaches the database.

To save the change, pass t to merge() and carry on with the object it returns. The same goes for deleting it: remove() only accepts a managed entity, so a detached one has to be merged first.