在交易功能中,调用clear()分离所有实体? [英] In a Transactional function, calling clear() detach all entities?
问题描述
我使用Hibernate作为JPA提供者,在一个函数中,我创建了一个不同实体的实例。一旦我为一个实体调用 clear()
,我不能在其他实体中使用 persist()
。我的代码非常复杂,并且我必须调用 flush()
和 clear()
一种类型的实体(而不是其他类型的实体),以释放一些内存。
简化我的代码如下:
@Transactional
void function()
{
EntityType1 entity1 = new EntityType1();
EntityType2 entity2 = new EntityType2();
// ......对entity1执行操作
entity1.persist();
entity1.flush();
entity1.clear();
// ......对entity2执行操作
entity2.persist();
当调用 entity2.persist()
我有以下错误:
org.springframework.orm.jpa.JpaSystemException:org.hibernate.PersistentObjectException:传递给持久化的分离实体
很可能您的 entity2
已经分配了 @Id
,因此Hibernate是期望更新现有的实体,而不是坚持一个新的实例。这就是为什么Hibernate认为 entity2
被分离的原因。
调用 entity2.merge()
将为您提供Hibernate会话的关联实体。被警告 merge()返回实体的一个新实例,即持久化副本。
示例
EntityType2 entityPersisted = entity2.merge();
entityPersisted.getSomething(); //你的持久实例
entity2.getSomething(); //仍然是分离的实例
调用 clear()清除您的整个会话缓存,因此您使用 @Id
将被视为独立。
如果您只想从会话缓存使用 evict()
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 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()
这篇关于在交易功能中,调用clear()分离所有实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!