Skip to content
Ameen Abozaid
Planned lessonMID-021-L04

Entity states revisited: merge vs persist

  • Lesson 4 of 6
  • Mid-level
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.
  • persist makes a new entity managed; merge copies 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 save calls persist for new entities and merge otherwise; merge of an unknown id may do an extra SELECT.
  • Prefer loading the entity inside the transaction and changing it (dirty checking) over merging DTO-built entities.
Draft outline details

Demonstration

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.