Hi guys,
I'm having a really hard time getting a straight answer to this question. There appears to be no doco anywhere on it. I will happily blog this for other people if somebody can resolve it for me!
If I have two session beans, Foo and Bar, that both use @Resource to inject an EntityManager...
Code:
@Stateful
class Foo {
@Resource EntityManager mEntityManager;
public void save( Company company ) {
getBean( Bar ).save( company ); // [1]
Company parentCompany = mEntityManager.find( parentCompanyId );
parentCompany.add( company ); // [3]
}
}
@Stateful
class Bar {
@Resource EntityManager mEntityManager;
public void save( Company company ) {
mEntityManager.merge( company ); // [2]
}
}
...such that...
1. Foo passes a (new) EntityBean to Bar
2. Bar saves it using its EntityManager
3. Foo adds it to a PersistentSet that cascades
...then I get all sorts of problems. @Resource appears to inject two separate EntityManagers, so they get very confused as they both try to persist company upon flush (one because of the explicit .merge, one because of the implicit cascade).
My question is:
Should you not try to use an EntityManager 'across beans'? Is there a way to have JPA inject the same EntityManager into both beans so that the transaction is coherent?Regards,
Richard.