1 抽取BaseDao
2 BaseDao设计思路
3 BaseDao接口书写
package www.test.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
public interface BaseDao<T> {
//增
void save(T t);
//删
void delete(T t);
//删 Serializable包括了8大包装类型
void delete(Serializable id);
//改
void update(T t);
//查 根据id查询
T getById(Serializable id);
//查 符合条件的总记录数
Integer getTotalCount(DetachedCriteria dc);
//查 查询分页列表数据
List<T> getPageList(DetachedCriteria dc,Integer start,Integer pageSize);
}
4 BaseDao的实现类
package www.test.dao.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import www.test.dao.BaseDao;
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
private Class clazz; // 用于接收运行期泛型类型
public BaseDaoImpl() {
// 获得当前类型的带有泛型类型的父类
// this.getClass().getGenericSuperclass();运行在BaseDaoImpl的儿子(谁继承了它)
// 所以它的父类就是BaseDaoImpl
ParameterizedType ptClass = (ParameterizedType) this.getClass().getGenericSuperclass();
// 获得运行期的泛型类型
clazz = (Class) ptClass.getActualTypeArguments()[0];
}
@Override
public void save(T t) {
super.getHibernateTemplate().save(t);
}
@Override
public void delete(T t) {
super.getHibernateTemplate().delete(t);
}
@Override
public void delete(Serializable id) {
// 先获取,然后在删除
T t = this.getById(id);
super.getHibernateTemplate().delete(t);
}
@Override
public void update(T t) {
super.getHibernateTemplate().update(t);
}
@Override
public T getById(Serializable id) {
return (T) super.getHibernateTemplate().get(clazz, id);
}
@Override
public Integer getTotalCount(DetachedCriteria dc) {
// 设置查询聚合函数,总记录数
dc.setProjection(Projections.rowCount());
List<Long> list = (List<Long>) super.getHibernateTemplate().findByCriteria(dc);
// 清空之前设置的聚合函数
dc.setProjection(null);
if (list != null && list.size() > 0) {
Long count = list.get(0);
return count.intValue();
} else {
return null;
}
}
@Override
public List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize) {
List<T> list = (List<T>) super.getHibernateTemplate().findByCriteria(dc, start, pageSize);
return list;
}
}
5 业务Dao中的应用
package www.test.dao;
import www.test.domain.Customer;
public interface CustomerDao extends BaseDao<Customer>{
}
package www.test.dao.impl;
import www.test.dao.CustomerDao;
import www.test.domain.Customer;
public class CustomerDaoImpl extends BaseDaoImpl<Customer> implements CustomerDao{
}