JPA
Hibernate
PersistentObjectException
Java programming
Database management

PersistentObjectException: detached entity passed to persist (JPA/Hibernate)

Codemia Knowledge Hub ·

PersistentObjectException: detached entity passed to persist means you called EntityManager.persist() on an entity that already has a database identity (a non-null @Id). Use merge() instead of persist() for detached entities, or make sure the entity is truly new before persisting it.

Entity lifecycle states

Every JPA entity is in one of four states, and this exception comes from confusing two of them:

StateHas @Id?Managed by EntityManager?In Database?
New / TransientNo (or null)NoNo
Managed / PersistentYesYesYes
DetachedYesNoYes
RemovedYesYes (scheduled for delete)Yes (until flush)

persist() expects a new entity with no database identity. If the entity has an @Id value and is not currently managed, JPA treats it as detached and throws:

java
1// This works: entity is new (transient)
2User user = new User();
3user.setName("Alice");
4entityManager.persist(user); // ID is null, so JPA assigns one
5
6// This throws PersistentObjectException: entity is detached
7User user = new User();
8user.setId(42L); // manually setting an ID makes it "detached"
9entityManager.persist(user); // ERROR: detached entity passed to persist

Five common causes and their fixes

1. Persisting an entity from a closed session

This is the most frequent cause. You load an entity, the EntityManager closes or the transaction ends, and you then persist the same object in a new context:

java
1// First transaction
2User user;
3EntityManager em1 = emf.createEntityManager();
4em1.getTransaction().begin();
5user = em1.find(User.class, 1L);
6em1.getTransaction().commit();
7em1.close(); // user is now DETACHED
8
9// Second transaction
10EntityManager em2 = emf.createEntityManager();
11em2.getTransaction().begin();
12user.setEmail("[email protected]");
13em2.persist(user); // ERROR: detached entity passed to persist
14em2.getTransaction().commit();

Fix: call merge() instead:

java
em2.merge(user); // This works for detached entities

2. Cascading persist to a detached parent

With CascadeType.PERSIST or CascadeType.ALL on a relationship, persisting the child cascades persist() to the parent. If the parent is detached, the cascade fails:

java
1@Entity
2public class Order {
3    @Id @GeneratedValue
4    private Long id;
5
6    @ManyToOne(cascade = CascadeType.ALL)
7    private Customer customer;
8}
9
10// customer was loaded in a previous session, now detached
11Customer customer = getExistingCustomer(); // detached entity
12
13Order order = new Order();
14order.setCustomer(customer); // associates detached customer
15
16entityManager.persist(order); // ERROR: cascades persist to detached customer

Fix: merge the parent first, or change the cascade type:

java
1// Option 1: merge the parent before persisting the child
2Customer managedCustomer = entityManager.merge(customer);
3order.setCustomer(managedCustomer);
4entityManager.persist(order);
5
6// Option 2: remove CascadeType.PERSIST from the relationship
7@ManyToOne // no cascade
8private Customer customer;

3. Setting the ID on a @GeneratedValue entity

If the entity uses @GeneratedValue but you set the ID yourself before persisting, Hibernate treats it as detached:

java
1@Entity
2public class Product {
3    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
4    private Long id;
5}
6
7Product product = new Product();
8product.setId(100L); // Don't do this with @GeneratedValue
9entityManager.persist(product); // ERROR or unexpected behavior

Fix: leave the @Id field unset when using @GeneratedValue and let Hibernate assign it.

4. Entities built from JSON or DTOs

When an entity arrives in a REST request body, JSON deserialization creates a new Java object with a populated ID that no persistence context manages:

java
1@PostMapping("/users")
2public void updateUser(@RequestBody User user) {
3    // user has an ID from the JSON body but is not managed
4    entityManager.persist(user); // ERROR: detached entity
5}

Fix: use merge(), or find the managed entity and update it. Find-then-update is more explicit and gives you control over what gets modified:

java
1// Option 1: merge
2entityManager.merge(user);
3
4// Option 2: find-then-update (more explicit, better control)
5User managed = entityManager.find(User.class, user.getId());
6managed.setName(user.getName());
7managed.setEmail(user.getEmail());
8// no persist needed, dirty checking handles the update

5. Bidirectional relationships with only one side set

With bidirectional @OneToMany / @ManyToOne mappings, failing to update both sides can leave detached references:

java
1@Entity
2public class Department {
3    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
4    private List<Employee> employees = new ArrayList<>();
5}
6
7@Entity
8public class Employee {
9    @ManyToOne
10    private Department department;
11}
12
13// Wrong: only setting one side
14Department dept = entityManager.find(Department.class, 1L);
15Employee emp = new Employee();
16emp.setDepartment(dept);
17// dept.getEmployees() still doesn't contain emp
18entityManager.persist(emp); // may cause issues with cascade

Fix: always synchronize both sides:

java
1Department dept = entityManager.find(Department.class, 1L);
2Employee emp = new Employee();
3emp.setDepartment(dept);
4dept.getEmployees().add(emp); // synchronize both sides
5entityManager.persist(emp);

persist() vs merge()

MethodInput StateWhat It DoesReturns
persist()Transient (new)Inserts a new row, assigns IDvoid (original object becomes managed)
merge()Detached or transientCopies state into a managed entity, inserts or updatesManaged copy (original stays detached)

merge() returns a new managed instance and leaves the object you passed in detached. Always keep working with the returned object:

java
1User detached = new User();
2detached.setId(42L);
3detached.setName("Bob");
4
5User managed = entityManager.merge(detached);
6
7// detached != managed (different object references)
8detached.setName("Alice"); // this change is NOT tracked
9managed.setName("Alice");  // this change IS tracked and will be flushed

Spring Data JPA's save() picks for you

Spring Data JPA's save() decides internally whether to call persist() or merge():

java
1@Repository
2public interface UserRepository extends JpaRepository<User, Long> {}
3
4// Spring calls persist() for new entities, merge() for existing ones
5userRepository.save(user); // works for both new and detached entities

It decides "new vs existing" by checking whether the @Id is null (for generated IDs), or through Persistable<ID> for assigned IDs:

java
1@Entity
2public class User implements Persistable<Long> {
3    @Id
4    private Long id;
5
6    @Transient
7    private boolean isNew = true;
8
9    @Override
10    public boolean isNew() {
11        return isNew;
12    }
13
14    @PostLoad
15    @PostPersist
16    void markNotNew() {
17        this.isNew = false;
18    }
19}

If you use raw JPA without Spring, you have to choose between persist() and merge() yourself.

Mistakes that cause or hide the error

  • Using merge() everywhere "just to be safe": merge() always issues a SELECT before the INSERT or UPDATE to check for existing records. For batch inserts of new entities, persist() is significantly faster because it skips that check.
  • CascadeType.ALL on @ManyToOne: this cascades persist() to the parent, which is almost always already persisted. Put CascadeType.ALL on the @OneToMany side and be selective on @ManyToOne.
  • Forgetting @GeneratedValue: without it, JPA does not generate IDs. An entity with a null @Id and no @GeneratedValue may be treated differently depending on the provider.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design