开发者

Why JPA injection not works on @PersistentUnit

开发者 https://www.devze.com 2022-12-25 08:23 出处:网络
It is continues of question ( struts 2 bean is not created ) 开发者_开发百科I\'m using struts2 + toplink in my very simple web application under Tomcat.

It is continues of question ( struts 2 bean is not created ) 开发者_开发百科I'm using struts2 + toplink in my very simple web application under Tomcat. On the page I would like use iteration tag. That is why I've declared some factory (SomeFactory) that resolves collection of entities (Entity). Per article: http://download-uk.oracle.com/docs/cd/B32110_01/web.1013/b28221/usclient005.htm#CIHCEHHG the only thing I need is declaration:

@PersistenceContext(unitName="name_in_persistence_xml")
public class SomeFactory
{
    @PersistenceUnit(unitName="name_in_persistence_xml")
    EntityManagerFactory emf;

    public EntityManager getEntityManager() {
       assert(emf != null); //HERE every time it is null
       return emf.createEntityManager();
    }
    public Collection<Entity> getAll()
    {
       return getEntityManager().createNamedQuery("Entity.findAll").getResultList();
}
}

What is wrong? May be i miss something in web.xml? How to pre-init toplink for web application to allow injection happen?


You won't get anything injected by Tomcat which is not a Java EE container (and even with a Java EE 5 container, injection only works for managed components like servlets, filters, listeners, EJB, web service endpoints...). So you will have to create the EntityManagerFactory manually (typically in a servlet or a helper class) and get the EntityManager from it:

EntityManagerFactory emf  = Persistence.createEntityManagerFactory(PU_NAME);
EntityManager entityManager = emf.createEntityManager();

Note that creating an EntityManagerFactory is a costly operation and should not be done for each request. However, creating an EntityManager is not and you should get one for each thread. But in your case, I'd suggest to use the struts2-persistenceplugin to handle this.

Thanks, but it seems [...] that Java EE is not mandatory to use injection [...] the Spring brings necessary engine for it.

Indeed. But you wrote "NO spring at all" in your other question and you didn't list any piece that could provide injection out of the box. Anyway, check out the struts2-persistenceplugin, it might be enough for your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消