Question

Sorry for the noob question, but I'm having problems with JPA+Hibernate so I thought that something is not clear in my mind. I have some entities, say A, B, C, D and I have coded AMethods, BMethods, CMethods, DMethods. Each of the *Methods classes contain EntityManager initialization via EntityManagerFactory and some methods that basically execute queries. I don't know if I should use a singleton pattern (so that I have an EntityManager per *Method class) or if I need to open and close the EntityManager each time I execute a query or I persist/remove an entity... can you help me??

Was it helpful?

Solution

In a typical JPA/Hibernate application, you don't put persistence logic in the entity classes themselves. This is a big change in design philosophy compared to older EJB 2.x applications. Instead, many applications create a layer of Data Access Objects--separate from the entities--that use EntityManager instances to query, load, and save entities. Often, these are singletons, and the entity manager instances inside the DAOs are local to the thread.

If you use a framework like Spring, the management of the EntityManager instances and transactions is completely automatic. Same with EJB 3, although I have not used that on a large project. I would suggest reading the Spring documentation's chapter on Object-Relational Mapping data access. Even if you don't end up using Spring in your application, the chapter gives some good tips on how to structure your application in a layered way that separates persistence concerns from the entities being persisted. Good luck!

OTHER TIPS

EntityManager is associated with a persistence context. Use a singleton pattern if all of yours entities are associated with one context. You use jpa on server side,right? If so you can initialized EntityManager in init methods, like init() on servlets.

just like this!

public interface ProtokollDAOService {

/**
 * Fügt ein Protokollobjekt in die Datenbank hinzu.
 * 
 * @param object
 */
public void addProtokoll (ProtokollModel object);

/**
 * Läd aus einer Datenbank Protokoll-Elemente und fügt sie in eine Liste hinzu
 * 
 * @return List <ProtokollModel> Liste mit Protokoll-Elementen 
 */
public List <ProtokollModel> getProtokolls ();

/**
 * Liefert ein Protokoll-Element aus der Datenbank anhand der ID; 
 * 
 * @param id
 * @return ProtokollModel Protokoll-Element 
 */
public ProtokollModel getProtokollById (long id);

/**
 * Liefert eine Liste von Protokoll-Elementen anhand des Problem-Status 
 * 
 * @param solved
 * @return List <ProtokollModel> Liste mit Protokoll-Elementen   
 */
public List <ProtokollModel> getProtokollByProblemStatus (boolean solved);

/**
 * Liefert eine Liste von Protokoll-Elementen anhand des Aufgaben-Status 
 * 
 * @param ready
 * @return List <ProtokollModel> Liste mit Protokoll-Elementen
 */
public List <ProtokollModel> getProtokollByAufgabenStatus (boolean ready);

/**
 * Liefert ein Protokoll-Element anhand des Problems
 * 
 * @param problem
 * @return List <ProtokollModel> Liste mit Protokoll-Elementen   
 */
public List <ProtokollModel> getProtokollByProblem (String problem);

/**
 * Liefert ein Protokoll-Element anhand der Aufgabe
 * 
 * @param aufgabe
 * @return List <ProtokollModel> Liste mit Protokoll-Elementen
 */
public List <ProtokollModel> getProtokollByAufgabe (String aufgabe);

/**
 * Ausgabe der Protokoll-Tabelle
 * 
 */
public void printTable ();

}

public class ProtokollDAOImpl implements ProtokollDAOService { private static final String PERSISTENCE_UNIT_NAME = "ProtokollManager"; private EntityManagerFactory entityFactory;

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#addProtokoll(model.ProtokollModel)
 */
public void addProtokoll(ProtokollModel object) {
    try
    {
        entityFactory = Persistence
                .createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = entityFactory.createEntityManager();

        // Transaction starten
        em.getTransaction().begin();

        // Object zum speichern
        em.persist(object);

        // commit senden an die DB / Transaction abschliessen
        em.getTransaction().commit();

        // DB connection schliessen
        em.close();
    }
    catch (Exception e)
    {
        Logger.console("Exception wurde ausgelösst! " + e);
        e.printStackTrace();
    }
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokollByAufgabe(java.lang.String)
 */
public List<ProtokollModel> getProtokollByAufgabe(String aufgabe) {
    // TODO Auto-generated method stub
    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokollByAufgabenStatus(boolean)
 */
public List<ProtokollModel> getProtokollByAufgabenStatus(boolean ready) {
    // TODO Auto-generated method stub
    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokollById(long)
 */
public ProtokollModel getProtokollById(long id) {
    try
    {
        entityFactory = Persistence
                .createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = entityFactory.createEntityManager();

        // Transaction starten
        em.getTransaction().begin();

        // Object aus der DB laden
        Query q = em.createQuery("select m from ProtokollModel m where m.id=:id");

        // Parameter setzen - siehe PreparedStatment
        q.setParameter("id", id);

        // liefert das Protokoll-Element zurück 
        ProtokollModel pm = (ProtokollModel) q.getSingleResult();

        // commit senden an die DB / Transaction abschliessen
        em.getTransaction().commit();

        // db connection schliessen
        em.close();

        return pm;
    }
    catch (Exception e)
    {
        Logger.console("Exception wurde ausgelösst! " + e);
        e.printStackTrace();
    } finally {

    }

    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokollByProblem(java.lang.String)
 */
public List<ProtokollModel> getProtokollByProblem(String problem) {
    // TODO Auto-generated method stub
    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokollByProblemStatus(boolean)
 */
public List<ProtokollModel> getProtokollByProblemStatus(boolean solved) {
    // TODO Auto-generated method stub
    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#getProtokolls()
 */
public List<ProtokollModel> getProtokolls() {
    // TODO Auto-generated method stub
    return null;
}

/*
 * (non-Javadoc)
 * 
 * @see util.ProtokollDAOService#printTable()
 */
public void printTable() {
    // TODO Auto-generated method stub
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top