一.为什么要抽取底层代码:
简化项目开发,减少重复代码,提高工作效率
二.DAO层抽取:
1.抽取原理:
2.dao接口:
/**
* 持久层通用接口
* @author
* @param <T>
*/
public interface IBaseDao<T> {
public void save(T entity);
public void delete(T entity);
public void update(T entity);
public T findById(Serializable id);
public List<T> findAll();
public void executeUpdate(String queryName,Object...object);
//通用分页查询方法
public void pageQuery(PageBean pageBean);
void saveOrUpdate(T entity);
List<T> findByCriteria(DetachedCriteria detachedCriteria);
}
3.接口实现类:
/**
* 持久层通用实现
* @author
*
* @param <T>
*/
public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T> {
//代表的是某个实体的类型
private Class<T> entityClass;
@Resource//根据类型注入spring工厂中的会话工厂对象sessionFactory
public void setMySessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
//在父类(BaseDaoImpl)的构造方法中动态获得entityClass
public BaseDaoImpl() {
ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();
//获得父类上声明的泛型数组
Type[] actualTypeArguments = superclass.getActualTypeArguments();
entityClass = (Class<T>) actualTypeArguments[0];
}
public void save(T entity) {
this.getHibernateTemplate().save(entity);
}
public void delete(T entity) {
this.getHibernateTemplate().delete(entity);
}
public void update(T entity) {
this.getHibernateTemplate().update(entity);
}public T findById(Serializable id) {
return this.getHibernateTemplate().get(entityClass, id);
}public List<T> findAll() {
String hql = "FROM " + entityClass.getSimpleName();
return (List<T>) this.getHibernateTemplate().find(hql);
}
@Override
public void executeUpdate(String queryName, Object... objects) {
Session session = this.getSessionFactory().getCurrentSession();
Query query = session.getNamedQuery(queryName);
int i = 0;
for (Object object : objects) {
//为HQL语句中的?赋值
query.setParameter(i++, object);
}
//执行更新
query.executeUpdate();
}/**
* 通用分页查询方法
*/
@Override
public void pageQuery(PageBean pageBean) {int currentPage = pageBean.getCurrentPage();
int pageSize = pageBean.getPageSize();
//查询数据总量封装pageBean对象
DetachedCriteria detachedCriteria = pageBean.getDetachedCriteria();
//设置查询count(*)
detachedCriteria.setProjection(Projections.rowCount());
List<Long> countList = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
Long count = countList.get(0);
pageBean.setTotal(count.intValue());
//清空detachedCriteria.setProjection(Projections.rowCount());
detachedCriteria.setProjection(null);
//指定hibernate封装对象的方式
detachedCriteria.setResultTransformer(DetachedCriteria.ROOT_ENTITY);
//封装private List rows ;
int firstResult = (currentPage - 1)*pageSize;
int maxResults = pageSize;
List rows = this.getHibernateTemplate().findByCriteria(detachedCriteria, firstResult, maxResults);
pageBean.setRows(rows);
}@Override
public void saveOrUpdate(T entity) {
this.getHibernateTemplate().saveOrUpdate(entity);
}@Override
public List<T> findByCriteria(DetachedCriteria detachedCriteria) {
return (List<T>) this.getHibernateTemplate().findByCriteria(detachedCriteria);
}
}
三.Action层代码抽取:
1.抽取原理:
2.代码实现:
/**
* 表现层通用实现
* @author zhaoqx
*
* @param <T>
*/
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
//***************************分页代码封装***************************************
// protected int rows ;
// protected int page ;
protected PageBean pageBean = new PageBean();
public void setRows(int rows) {
pageBean.setPageSize(rows);
}
public void setPage(int page) {
pageBean.setCurrentPage(page);
}
DetachedCriteria detachedCriteria = null;
/**
* 将制定java对象转换为json对象,并响应到客户端
* @param o
* @param excludes
*/
public void java4Json(Object o,String[] excludes) {
//JSONArray----将数组或者集合对象转为json
JsonConfig jsonConfig = new JsonConfig();
//指定哪些属性不需要转json
jsonConfig.setExcludes(excludes);
String json = JSONObject.fromObject(o,jsonConfig).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
try {
ServletActionContext.getResponse().getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
//方法重载
public void java4Json(List list,String[] excludes) {
//JSONArray----将数组或者集合对象转为json
JsonConfig jsonConfig = new JsonConfig();
//指定哪些属性不需要转json
jsonConfig.setExcludes(excludes);
String json = JSONArray.fromObject(list,jsonConfig).toString();
ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
try {
ServletActionContext.getResponse().getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
//**************************************************************
public static final String HOME = "home";
//模型对象
protected T model;
public T getModel() {
return model;
}
//在构造方法中动态获取实体类型,通过反射创建model对象
public BaseAction() {
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
//获得BaseAction上声明的泛型数组
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
Class<T> entityClass = (Class<T>) actualTypeArguments[0];
//-----------------分页封装代码--------------------
detachedCriteria = DetachedCriteria.forClass(entityClass);
pageBean.setDetachedCriteria(detachedCriteria);
//---------------------------------------
//通过反射创建对象
try {
model = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
四:PageBean分页工具抽取:
import org.hibernate.criterion.DetachedCriteria;
/**
* 封装分页工具类
* @author Administrator
*
*/
public class PageBean {
private int currentPage ; //当前页码
private int pageSize ; //每页现实的记录数
private int total ; //记录的总数
private DetachedCriteria detachedCriteria ; //离线查询条件
private List rows ; //当前页需要展示的数据集合
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public DetachedCriteria getDetachedCriteria() {
return detachedCriteria;
}
public void setDetachedCriteria(DetachedCriteria detachedCriteria) {
this.detachedCriteria = detachedCriteria;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}