Entity states revisited: merge vs persist
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
handle detached entities correctly.
Planned topics
- States: transient (new), managed (in the persistence context), detached (loaded earlier, session closed), removed.
persistmakes a new entity managed;mergecopies the state of a detached entity onto a managed copy and returns that copy.- Use the returned object from
merge; the argument stays detached. - Spring Data
savecallspersistfor new entities andmergeotherwise;mergeof an unknown id may do an extraSELECT. - Prefer loading the entity inside the transaction and changing it (dirty checking) over merging DTO-built entities.
Draft outline details
Demonstration
Product managed = em.merge(detached); // use 'managed', not 'detached'Check your understanding
What does merge return?
Show answer
The managed copy; the passed object stays detached.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.