users@glassfish.java.net

Dependency injection problems

From: <glassfish_at_javadesktop.org>
Date: Wed, 18 Feb 2009 20:18:19 PST

Hi All,

I am attempting to implement some Audit logging into a db of a EJB3 / Java EE 5 application.

I have mapped Listeners to selected Entities where I will insert Auditing records into a db where required.

The methods in my Listener classes that are annotated with @PrePersist, @PreUpdate etc are being triggered ok, however I can't
get the EntityManager to be injected into the listener.

I have only been able to inject an EntityManager into a EJB Bean class.

I have tried injecting a EntityManagerFactory without success.
ie. @PersistenceUnit EntityManagerFactory emf;

I have included a code snippet.

Thanks in advance,
Adam


import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless(name = "TestServiceBean", mappedName = "TestServiceBean")
@WebService
public class TestServiceBean implements TestService {

        @Resource
    protected SessionContext ctx;

    @PersistenceContext(unitName = "em")
    protected EntityManager em;

    public void create() {
        
                MyEntity entity = new MyEntity();
                entity.setValue("foo");
                
                em.persist(entity);
                
    }
}

@Entity
@EntityListeners({MyEntityListener.class })
@Table(schema = "schema_name", name = "my_entity")
public class MyEntity implements Serializable {
        .
        .
        .
}

public class MyEntityListener {

    @PersistenceContext(unitName = "em")
    EntityManager em;

    @PersistenceUnit
    protected EntityManagerFactory emf;

    @PrePersist
    public void prePersist(Object object) {
        
                // EntityManager has not been injected. em is null
                
                // Insert Audit rec into db here
    }

}
[Message sent by forum member 'brabble' (brabble)]

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