views:

1657

answers:

3

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??

+1  A: 

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.

merin
I use the same persistence context, every entity is associated with one context. I use jpa on server side but I use it also in a java application running in background... I should initialize the context in this app and create *Methods passing the EntityManager as parameter??
Raffo
Yes, If service and your backgound application are difeerent applications it is necessary initiate EntityManager for both. I think it would be a hard task to serialize EntityMaanger instance.
merin
Use Spring, use Hibernate. Why Ejb?
merin
I just used JPA as explained here: http://java.sun.com/javaee/5/docs/tutorial/doc/bnbpz.html. Is there something wrong with my approach?
Raffo
JPA use as underline ORM like a driver. Why you don't use ORM without any abstractions?
merin
So you think I should create objects and let JPA do the rest? I used the approach explained in the topic because I found it easier in order to get all the entities that satisfy a condition (using queries) and to persist a lot of entities at once...
Raffo
+1  A: 

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!

Rob H
I don't use Spring and I'm using DAOs as explained (the DAOs are the *Methods classes) but they all use the same persistence context. It's correct to exec createEntityManager in AMethods and also in BMethods even if they use the same persistence context??
Raffo
A: 

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
}

}

Marco