views:

81

answers:

2

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?

A: 

You could consider using Spring 3. Just follow their documentation for a clean design.

Damien
+1  A: 

Personally, I don't see the added value of shielding the EntityManager (which is an implementation of the Domain Store pattern) with a DAO and I would use it directly from the services, unless switching from JPA is a likely event. But, quoting An interesting debate about JPA and the DAO:

Adam said that he met only very few cases in which a project switched the database vendor, and no cases in which the persistence moved to a different thing than a RDBMs. Why should you pay more for a thing that it's unlikely to happen? Sometimes, when it happens, a simpler solution might have paid for itself and it might turn out to be simpler to rewrite a component.

I totally share the above point of view.

Anyway, the question that remains open is the lifecycle of the EntityManager and the answer highly depends on the nature of your application (a web application, a desktop application).

Here are some links that might help to decide what would be appropriate in your case:

And if you really want to go the DAO way, you could:

Pascal Thivent