views:

50

answers:

1

Hello colleagues! It is continues of question ( http://stackoverflow.com/questions/2570976/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?

A: 

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.

Pascal Thivent
Thanks, but it seems (I mean 'seems' since I have not real knowledge about this) that Java EE is not mandatory to use injection. Looking at sample http://struts.apache.org/2.x/docs/struts-2-spring-2-jpa-ajax.html - the Spring brings necessary engine for it. So could you explain: can I use xwork (that is already part of struts2) to implement injection in the same way as spring does?
Dewfy