Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: question about merging an entity before removing it

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);
}
like image 250
Thang Pham Avatar asked Oct 06 '10 21:10

Thang Pham


2 Answers

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.

like image 117
Pascal Thivent Avatar answered Nov 15 '22 22:11

Pascal Thivent


...and you can even combine those:

Like so:

    public void deleteManCheck(ManCheck manCheck) {
    em.remove(em.merge(manCheck));
}
like image 44
jos de jong Avatar answered Nov 15 '22 21:11

jos de jong