I've JPA entities and need to perform logic with them. Until now a huge static database class did the job. It's ugly because every public interface method had an private equivalent that used the EntityManager, to perform transactions. But I could solve that having a static em too! However i'm wondering if that's an appropriate design, especially as the class is responsible for many things. Not surprisingly, the code i found online of real projects was not easy to understand (i might then as well remeain with my code). The code here is easy to understand, although maybe over generic? Anyway, on top of JDBC. Yet, insightful, why use factories and singletons for DAOs?
I've though of singletoning the em instance as follows:
private static final Map<String, EntityManager> ems = new HashMap<String, EntityManager>();
private final EntityManager em;
private final EntityManagerFactory emf;
public void beginTransaction() {
em.getTransaction().begin();
}
public void commitTransaction() {
em.getTransaction().commit();
}
public Database(final String persistenceUnitName) {
if(ems.containsKey(persistenceUnitName)){
em = ems.get(persistenceUnitName);
}else{
ems.put(persistenceUnitName, em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager());
}
emf = em.getEntityManagerFactory();
this.persistenceUnitName = persistenceUnitName;
}
This way creation of instances is standard, still maintaining a singleton Connection/EntityManager. On the otherhand I wondered whether there was the need to singleton ems in the first place? The advantage is with multiple ems I run into locking problems (not using em.lock()).
Any feedback? Any real-world or tutorial code that demonstrates DAO with JPA2 and eclipselink?