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 cn.zhuqi.mavenssh.dao.impl; import cn.zhuqi.mavenssh.dao.IGenericDAO; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; /** * * @author Administrator * @param <T> */ public class GenericDAO<T> implements IGenericDAO<T> { private final Class<T> entityClass; public GenericDAO(Class<T> entityClass) { this.entityClass = entityClass; } @Autowired private SessionFactory sessionFactory; protected Session getSession() { return sessionFactory.getCurrentSession(); } @Override public void insert(T t) { getSession().save(t); } @Override public void delete(T t) { getSession().delete(t); } @Override public void update(T t) { getSession().merge(t); } @SuppressWarnings("unchecked") @Override public T queryById(Integer id) { return (T) getSession().get(entityClass, id); } @Override public List<T> queryAll() { String hql = "from " + entityClass.getSimpleName(); return queryForList(hql, null); } @SuppressWarnings("unchecked") protected T queryForObject(String hql, Object[] params) { Query query = getSession().createQuery(hql); setQueryParams(query, params); return (T) query.uniqueResult(); } @SuppressWarnings("unchecked") protected T queryForTopObject(String hql, Object[] params) { Query query = getSession().createQuery(hql); setQueryParams(query, params); return (T) query.setFirstResult(0).setMaxResults(1).uniqueResult(); } @SuppressWarnings("unchecked") protected List<T> queryForList(String hql, Object[] params) { Query query = getSession().createQuery(hql); setQueryParams(query, params); return query.list(); } @SuppressWarnings("unchecked") protected List<T> queryForList(final String hql, final Object[] params, final int recordNum) { Query query = getSession().createQuery(hql); setQueryParams(query, params); return query.setFirstResult(0).setMaxResults(recordNum).list(); } private void setQueryParams(Query query, Object[] params) { if (null == params) { return; } for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } } }