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

末鹿安然 提交于 2019-12-11 02:41:48

问题


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


回答1:


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()



来源:https://stackoverflow.com/questions/11903653/in-a-transactional-function-calling-clear-detach-all-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!