1.BaseDao接口
package com.learning.crm.base; import java.io.Serializable; import java.util.List; public interface BaseDao<T> { /** * 保存 * @param t */ public void save(T t); /** * 更新 * @param t */ public void update(T t); /** * 查询所有 * @return */ public List<T> findAll(); /** * 根据id查询 * @param id * @return */ public T findById(Serializable id); /** * 删除 * @param t */ public void delete(T t); /** * 条件加分页查询 * @param t * @param pageSize * @param currentPage * @return */ List<T> findAll(final String condition,final Object[] objects, final int pageSize, final int currentPage); }
2.BaseDaoImpl:
package com.learning.crm.base.impl; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.learning.crm.base.BaseDao; public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{ private Class<?> clazz; public BaseDaoImpl() throws InstantiationException, IllegalAccessException { //获得T ParameterizedType parameterizedType= (ParameterizedType) this.getClass().getGenericSuperclass(); //获得运行时的T类型 clazz = (Class<?>) parameterizedType.getActualTypeArguments()[0]; } @Override public List<T> findAll(String condition,final Object[] objects, final int pageSize, final int currentPage) { final String hql="from "+clazz.getName()+" where 1=1 "+condition; return this.getHibernateTemplate().execute(new HibernateCallback<List<T>>() { public List<T> doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); } query.setFirstResult((currentPage-1)*pageSize); query.setMaxResults(pageSize); return query.list(); } }); } @Override public void save(T t) { this.getHibernateTemplate().save(t); } @Override public void update(T t) { this.getHibernateTemplate().update(t); } @Override public List<T> findAll() { return this.getHibernateTemplate().find(" from "+ clazz.getName()); } @Override public T findById(Serializable id) { this.getHibernateTemplate().get(clazz, id); return null; } @Override public void delete(T t) { this.getHibernateTemplate().delete(t); } }
3.编写自己的Dao时,比如UserDao要继承BaseDao,UserDaoImpl要实现UserDao,继承BaseDaoImpl