Hello, we are developing a J2SE application and we are using Hibernate for our persistence layer. For our database access I created a singleton class that has all the necessary methods to obtain and persist objects from the database. But once I created the second method for obtaining objects I immediately realized that I have a smelly code:
public enum DataManager {
Instance;
public List<Employee> getEmployees() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
List<?> ems = em.createQuery("select e from Employee e").getResultList();
List<Employee> result = new ArrayList<Employee>();
for (Object o : ems )
result.add((Employee) o);
tx.commit();
em.close();
emf.close();
return result;
}
public List<Shift> getShifts() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
List<?> ems = em.createQuery("select s from Shift s").getResultList();
List<Shift> result = new ArrayList<Shift>();
for (Object o : ems )
result.add((Shift) o);
tx.commit();
em.close();
emf.close();
return result;
}
}
So I definitely need to redesign this. The Hibernate documentation has a HibernateUtility class for Session handling and Transactions. But I use EntityManager.
Just yesterday I found this very interesting article called Generic DAO pattern with JDK 5.0. It is written in 2005 so I really not sure if it is still valid. It again uses Sessions.
Is this what you use? If not, have a better solution?
Thank you.
Note1: I'm fairly new to Hibernate
Note2: The title doesn't seem right