JPA:在删除实体之前合并一个实体的问题 [英] JPA: question about merging an entity before removing it
问题描述
e =(Event)scholarBean.merge(e);
scholarBean.remove(e);
在我的托管bean中。它给我这个错误
java.lang.IllegalArgumentException:实体必须被管理才能调用remove:com.scholar.entity.Event @ 998,尝试合并分离,再次尝试删除。
所以我把这两行插入我的会话bean,它的工作原理。任何想法为什么?
托管Bean
myEJB.deleteEvent(E);
和
myEJB.java
public void deleteEvent(Event e){
e = )merge(e);
em.remove(e);
}
我知道我必须在删除它之前合并实体。
不完全是。传递给remove的对象必须是一个实体,不能被分离。这是不同的。
但我从来没有想过我必须在EJB内完成。首先我有这些(...)
让我们看看你在做什么:
1:e =(Event)scholarBean.merge(e);
2:scholarBean.remove(e);
所以在 1:
中,你叫EJB(非常有可能使用事务范围的Persistence Context)来合并实体。但是方法结束,事务提交,持久性上下文关闭,使返回的实体再次分离。
而在$ code> 2:,您将(静态)分离的实体传递给EJB,并尝试删除
,这是不允许的。和KaBOOM!
所以我把这两行插入我的会话bean,它的工作原理。任何想法为什么?
它的工作原理是因为您正在与JTA事务关联的持久性上下文的范围内工作,因此真正将管理实体传递给删除
。
I know I have to merge the entity before removing it, but I never thought I have to do it inside EJB. First I have these:
e = (Event) scholarBean.merge(e);
scholarBean.remove(e);
in my managed bean. It give me this error
java.lang.IllegalArgumentException: Entity must be managed to call remove: com.scholar.entity.Event@998, try merging the detached and try the remove again.
So then I bring those two lines inside my session bean, and it works. Any idea why?
Managed Bean
myEJB.deleteEvent(e);
and
myEJB.java
public void deleteEvent(Event e){
e = (Event) merge(e);
em.remove(e);
}
I know I have to merge the entity before removing it
Not exactly. The object passed to remove has to be an entity and must not be detached. That's different.
but I never thought I have to do it inside EJB. First I have these (...)
Let's see what you're doing:
1: e = (Event) scholarBean.merge(e);
2: scholarBean.remove(e);
So in 1:
, you call an EJB (very likely with a transaction-scoped Persistence Context) that merges the entity. But then the method ends, the transaction commits, the Persistence Context gets closed, making the returned entity detached again.
And in 2:
, you pass the (still) detached entity to an EJB and tries to remove
it, which is not allowed. And KaBOOM!
So then I bring those two lines inside my session bean, and it works. Any idea why?
It works because you're now working within the scope of the persistence context associated to the JTA transaction and you're thus really passing a managed entity to remove
.
这篇关于JPA:在删除实体之前合并一个实体的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!