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
Most likely your
entity2already has an@Idassigned and therefore Hibernate is expecting to Update the existing entity rather than persist a new instance. This is why Hibernate considersentity2to 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
Calling clear() evicts your entire session cache so all entites you have with an
@Idwill be considered detached.If you only want to remove the one entity from the session cache use evict()