users@glassfish.java.net

Re: Lifecycle callbacks and enterprise bean's environment

From: <glassfish_at_javadesktop.org>
Date: Mon, 21 Jan 2008 00:02:50 PST

The entity manager can be looked up according to the JPA specs (ยง5.2.1):

@Stateless
@PersistenceContext(name="OrderEM")
public class MySessionBean implements MyInterface {
@Resource SessionContext ctx;
public void doSomething() {
EntityManager em = (EntityManager)ctx.lookup("OrderEM");
...
}
}

You will probably need to add the @PersistenceUnit annotation on all your EJBs. Note that "OrderEM" is not the name of the persistence unit, but the local name that you want in JNDI. You can have for instance:

<persistence-unit name="sample">
@PersistenceContext(name="sampleEM", unitName="sample")
EntityManager em = (EntityManager)ctx.lookup("sampleEM");

However, I don't think that you are allowed to use the entityManager in a callback method. The Hibernate documentation states that "A callback method must not invoke EntityManager or Query methods!". See http://www.hibernate.org/hib_docs/entitymanager/reference/en/html/listeners.html
This recommandation probably holds also for Toplink.

I noticed for instance that the @PostPersist callback method may be called after the transaction has been committed. What happen then if you try to persist another entity in the callback ? If you really want to do such things, I think that @PrePersist is safer (but I still don't think it is the best way).

You can configure operations on an entity to be cascade or not - this is maybe something to investigate in your case.
[Message sent by forum member 'ewernli' (ewernli)]

http://forums.java.net/jive/thread.jspa?messageID=254935