I am building a simple web application for which I would like to use JPA. Although I expect to be deploying on Glassfish I was think that it may be beneficial to manage entity persistence within the application rather than through JTA datasource. I acknowledge that this may not be a very bright idea?
Some time ago I put the following together (possibly from a now lost web reference):
public class PersistenceManager {
private static final PersistenceManager instance = new PersistenceManager();
protected EntityManagerFactory emf;
public static PersistenceManager getInstance() {
return instance;
}
private PersistenceManager() {
}
public EntityManagerFactory getEntityManagerFactory() {
if (emf == null) {
createEntityManagerFactory();
}
return emf;
}
public void closeEntityManagerFactory() {
if (emf != null) {
emf.close();
emf = null;
}
}
protected void createEntityManagerFactory() {
this.emf = Persistence.createEntityManagerFactory("Met");
}
}
So, my questions; Is this a reasonable approach – are there any pitfalls here?
I’ve always deployed JPA without container managed persistence. I’ve even used it with Atomikos JTA transaction manager. The simplest way is to not use JNDI based lookup. I would recomment using Spring’s JPATransactionManager and to configure everything either with persistence.xml or spring-xml.
Persistence manager in Spring-xml:
Don’t specify non-jta or jta-data-source tags in persistence.xml. The rest of the setup is standard-spring (EntityManagerFactory, DataSource etc.).