问题
I use OpenJPA on WebSphere Application Server. My WebApplication uses JSF 2 (without EJB).
I wanted to know if there are best practices how to use JPA in JSF.
I found that the EntityManagerFactory (EMF) should be application scoped. Also the EMF should be (only) destroyed when the application stops.
But my sources are not the newest:
Java Notepad: JPA EMF in web applications from 2007
Best way to use JPA in web-tier from 2010
How to close a JPA EntityManger in web applications from 2007
Are there other practices or better ways to handle JPA in JSF? Especially Scope of EMF and DAO.
Best Regards, Veote
回答1:
Create a simple servlet filter which creates the EMF in init()
method, closes it in destroy()
method and creates an EntityManager
in doFilter()
method which get set as a ThreadLocal<EntityManager>
. You can also begin and end the transactions in there.
This is also known as the "open session in view" or "open entitymanager in view" pattern.
来源:https://stackoverflow.com/questions/11607664/how-to-use-openjpa-entitymanagerfactory-in-jsf