Search code examples
springhibernatejpatransactionalpersist

In a Transactional function, calling clear() detach all entities?


I am using Hibernate as JPA provider and in a function, I am creating an instance of different entities. Once I call clear() for one entity, I can't persist() the other entities. My code is pretty more complicated, and at a point I am obliged to call flush() and clear() for one type of entities (and NOT for the other types) in order to free some memory.

A simplification of my code is as follow:

@Transactional
void function()
{
    EntityType1 entity1 = new  EntityType1();
    EntityType2 entity2 = new  EntityType2();

    //...... do operations on entity1
    entity1.persist();
    entity1.flush();
    entity1.clear();

    //...... do operations on entity2
    entity2.persist();
}

When calling entity2.persist() I have the following error: org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: detached entity passed to persist


Solution

  • Most likely your entity2 already has an @Id assigned and therefore Hibernate is expecting to Update the existing entity rather than persist a new instance. This is why Hibernate considers entity2 to be detached.

    Calling entity2.merge() will provide you with an associated entity to the Hibernate session. Be warned that merge() returns a new instance of your entity that is the persisted copy.

    Example

    EntityType2 entityPersisted = entity2.merge();
    
    entityPersisted.getSomething();  // your persisted instance
    entity2.getSomething();  // still your detached instance
    

    Calling clear() evicts your entire session cache so all entites you have with an @Id will be considered detached.

    If you only want to remove the one entity from the session cache use evict()