package auction.dao.hibernate; import auction.dao.*; import auction.persistence.HibernateUtil; import org.hibernate.*; import org.hibernate.criterion.*; import java.util.*; import java.io.Serializable; import java.lang.reflect.ParameterizedType; /** * Implements the generic CRUD data access operations using Hibernate APIs. *

* To write a DAO, subclass and parameterize this class with your persistent class. * Of course, assuming that you have a traditional 1:1 appraoch for Entity:DAO design. *

* You have to inject a current Hibernate Session to use a DAO. Otherwise, this * generic implementation will use HibernateUtil.getSessionFactory() to obtain the * curren Session. * * @see HibernateDAOFactory * * @author Christian Bauer */ public abstract class GenericHibernateDAO implements GenericDAO { private Class persistentClass; private Session session; public GenericHibernateDAO() { this.persistentClass = (Class) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } public void setSession(Session s) { this.session = s; } protected Session getSession() { if (session == null) session = HibernateUtil.getSessionFactory().getCurrentSession(); return session; } public Class getPersistentClass() { return persistentClass; } @SuppressWarnings("unchecked") public T findById(ID id, boolean lock) { T entity; if (lock) entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE); else entity = (T) getSession().load(getPersistentClass(), id); return entity; } @SuppressWarnings("unchecked") public List findAll() { return findByCriteria(); } @SuppressWarnings("unchecked") public List findByExample(T exampleInstance, String... excludeProperty) { Criteria crit = getSession().createCriteria(getPersistentClass()); Example example = Example.create(exampleInstance); for (String exclude : excludeProperty) { example.excludeProperty(exclude); } crit.add(example); return crit.list(); } @SuppressWarnings("unchecked") public T makePersistent(T entity) { getSession().saveOrUpdate(entity); return entity; } public void makeTransient(T entity) { getSession().delete(entity); } public void flush() { getSession().flush(); } public void clear() { getSession().clear(); } /** * Use this inside subclasses as a convenience method. */ @SuppressWarnings("unchecked") protected List findByCriteria(Criterion... criterion) { Criteria crit = getSession().createCriteria(getPersistentClass()); for (Criterion c : criterion) { crit.add(c); } return crit.list(); } }