I have JPA entities and you need to follow the logic with them. So far, a huge static database class has been doing this job. This is ugly because every open interface method had a private equivalent that EntityManager used to execute transactions. But I could decide that with their static too! However, I wonder if this is appropriate for the design, especially since the class is responsible for many things. Not surprisingly, the code that I found online in real projects was not easy to understand (then I could also fix my code). Is the code easy to understand here , although it may be more general? Anyway, on top of JDBC. However insightful, why use factories and singleton for DAO?
I have at least a singleton instance of em 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; }
Thus, instantiation is standard, still supporting singleton Connection / EntityManager. On the other hand, I wondered if a singleton was needed first. The advantage is that with several ems I run into blocking problems (not using em.lock ()).
Any feedback? Any real or tutorial code demonstrating DAO with JPA2 and eclipselink?
simpatico Sep 15 '10 at 2:56
source share