English 中文(简体)
Using JSF, JPA and DAO. Without Spring?
原标题:

till now i still worked with JSF and JPA without DAOs. Now i d like to use DAOs. But how can i initialize the EntityManager in the DAO-Classes?

public class AdresseHome {

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Adresse transientInstance) {
        log.debug("persisting Adresse instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }
}

Have I to use Spring or is there a solution that works without Spring?

Thanks.

最佳回答

If your container doesn t inject the EntityManager for you, you can get one with:

EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("jpatest");
EntityManager em = factory.createEntityManager();

Where "jpatest" from the unit defined in your persistence.xml

问题回答

Java EE 5 doesn t support injection in non managed component so without Spring you ll have to use an application-managed entity manager here (and consequently to manage its lifecycle at the application level).

Actually, Java EE 5+ doesn t really advocates using the DAO pattern (Has JPA Killed the DAO? is a nice article on this topic) and wrapping the entity manager which implements the Domain Store pattern, which does pretty much of what DAO does, in a DAO doesn t really make sense in my opinion.

Another option for you is to implement your DAO itself as a SLSB. That way you can inject the EntityManger rather than creating it. But it has it s own bad effects like too many session beans. chaining of the beans etc which is a sort of bad parctice.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签