Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chiron.maxscore.dao.impl; import chiron.maxscore.dao.BaseDAO; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.beans.factory.annotation.Autowired; /** * Hibernate BaseDAOImpl * * @author Diluka * @param <E> */ public abstract class BaseDAOImpl<E> implements BaseDAO<E> { /** * */ private final Class<E> entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; /** * Hibernate Session */ @Autowired protected SessionFactory sessionFactory; /** * ? * * @param id * @return null */ @Override public E getById(Serializable id) { Session session = sessionFactory.getCurrentSession(); Object o = session.get(entityClass, id); return o == null ? null : (E) o; } /** * ? * * @param e */ @Override public void save(E e) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(e); } /** * * * @param e */ @Override public void delete(E e) { Session session = sessionFactory.getCurrentSession(); session.delete(e); } /** * ? * * @return List */ @Override public List<E> getAll() { Session session = sessionFactory.getCurrentSession(); return session.createCriteria(entityClass).list(); } /** * * * @param start ? * @param limit ? * @param criteria ? * @return List */ @Override public List<E> search(int start, int limit, DetachedCriteria criteria) { Session session = sessionFactory.getCurrentSession(); return criteria.getExecutableCriteria(session).setFirstResult(start).setMaxResults(limit).list(); } /** * ?? * * @param criteria ? * @return */ @Override public int count(DetachedCriteria criteria) { Session session = sessionFactory.getCurrentSession(); return ((Number) criteria.setProjection(Projections.rowCount()).getExecutableCriteria(session) .uniqueResult()).intValue(); } }