In my web application, there are quite a few entities, and most of them require CRUD operations. So I am thinking about writing a generic DAO that can handle CRUD for all of the entities. I've found a tutorial article from IBM, but don't quite understand the generic implementation using the generic type 'T', and 'PK'. The article is at this link
I wrote the following DAO by using Object type in all the methods, and they seem working just fine - all my entities are able to do CRUD with the following CommonDao class. Although it works for my needs, I'm looking for what is the best practice for implementing a generic DAO class for Hibernate.
public class CommonDao
{
private final static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public CommonDao() {}
@UnitOfWork
public List findAll(Object className)
{
List types = null;
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(className + ".class");
types = (List <Object>) criteria.list();
session.close();
return types;
}
@Transactional
public void saveObject(Object obj)
{
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
session.close();
}
@Transactional
public void saveObjectWithManyEntities(Object obj, Set<Object> objects) /* for OneToMany relationships */
{
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
for (Object o : objects)
{
session.save(o);
}
tx.commit();
session.close();
}
}