Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

JPA/Hibernate: detached entity passed to persist

Asked by Aashna Saito Jun 9, 2021 21.8K views 3 answers
Share

About this question

What is a detached entity passed to persist? what is that detached entity the message talks about? 

 I have a JPA-persisted object model that contains a many-to-one relationship: an Account has many Transactions. A Transaction has one Account.

Here's a snippet of the code:

@Entity
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    private Account fromAccount;
....
@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany(cascade = {CascadeType.ALL},fetch= FetchType.EAGER, mappedBy = "fromAccount")
    private Set transactions;

I am able to create an Account object, add transactions to it, and persist the Account object correctly. But, when I create a transaction, using an existing already persisted Account, and persisting the Transaction, I get an exception:

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.paulsanwald.Account at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141)

So, I am able to persist an Account that contains transactions, but not a Transaction that has an Account. I thought this was because the Account might not be attached, but this code still gives me the same exception:

if (account.getId()!=null) {
    account = entityManager.merge(account);
}
Transaction transaction = new Transaction(account,"other stuff");
 // the below fails with a "detached entity" message. why?
entityManager.persist(transaction);

How can I correctly save a Transaction, associated with an already persisted Account object?

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 4, 2025

The "detached entity passed to persist" error in JPA/Hibernate typically occurs when you try to persist an entity that is already in a detached state. Hibernate expects a new (transient) entity when using persist(), but if the entity was previously managed and then detached, this error appears. Here’s how you can fix it:

1. Understand the Issue

  • When an entity is detached, Hibernate no longer tracks its changes.
  • If you try to use persist(), Hibernate expects a brand-new entity, not a detached one.

2. Solutions to Fix the Error

✅ Use merge() Instead of persist()

If the entity is detached but you still need to update it:

  entityManager.merge(detachedEntity);

merge() reattaches the entity to the persistence context.

✅ Ensure Entity is in a Managed State

If you’re persisting an entity that was retrieved earlier, make sure it’s still managed:

Entity managedEntity = entityManager.find(Entity.class, detachedEntity.getId());
entityManager.persist(managedEntity);

Use find() or getReference() to fetch a managed version before persisting.

✅ Remove persist() on an Existing Entity

persist() is meant for new entities only. If the entity already exists in the database, use merge() instead.

✅ Check Cascade Type

If you're working with related entities, make sure CascadeType.MERGE is applied:

@OneToMany(mappedBy = "parent", cascade = CascadeType.MERGE)
private List children;

3. Debugging Steps

  • Print entityManager.contains(yourEntity) to check if it's managed.
  • Enable Hibernate logs to track entity states.

Summary

  • Use merge() instead of persist() for existing entities.
  • Ensure the entity is managed before persisting.
  • Check cascade settings for related entities.

Let me know if you need more details!

Was this helpful?

Ranjana Admin JanBask Expert

Answered on Apr 26, 2024

The "Detached entity passed to persist" error in JPA/Hibernate occurs when you attempt to persist an entity that was previously fetched from the database and is now in a detached state. This typically happens when an entity has been retrieved in one transaction, and then an attempt is made to persist it in another transaction.


To resolve this issue, you can:

Reattach the Entity: If you intend to update the entity, you can reattach it to the current persistence context using the merge() method. This method merges the state of the detached entity with the persistence context and returns a managed entity, which can then be persisted.

entityManager.merge(entity);

Use persist() for New Entities: If the entity is new and not yet managed by the persistence context, you should use the persist() method to make it persistent.

entityManager.persist(entity);

Fetch and Update in the Same Transaction: If possible, perform both fetching and updating of entities within the same transaction to keep them attached to the persistence context.

Check Cascade Settings: Ensure that cascade settings are appropriately configured for relationships between entities. If cascading is set to ALL or MERGE, associated entities will be persisted along with the main entity.

By applying these strategies, you can handle the "Detached entity passed to persist" error effectively in your JPA/Hibernate application.




Was this helpful?

More Java discussions