SHS框架下的basedao 很有用的 核心类

import java.io.Serializable;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.framework.commons.pagination.Page;
import com.framework.commons.pagination.PageConstant;
import com.framework.commons.utils.EntityDao;
import com.framework.commons.utils.ParamValidate;
import com.framework.commons.utils.StringUtils;


/**
 * 负责为单个Entity对象提供CRUD操作的Hibernate DAO基类. <p/> 子类只要在类定义时指定所管理Entity的Class,
 * 即拥有对单个Entity对象的CRUD操作.
 *
 * <pre>
 * public class UserManager extends HibernateEntityDao&lt;User&gt; {
 * }
 * </pre>
 *
 * @author calvin
 * @see HibernateGenericDao
 */
@SuppressWarnings("unchecked")
public abstract class HibernateEntityDao<T> extends HibernateGenericDao
  implements EntityDao<T> {

 protected Class<T> entityClass;

 /**
  * findById
  *
  * @param id
  * @return
  */
 public T findById(Serializable id) {
  return findById(getEntityClass(), id);
 }

 /**
  * 批量删除
  * @param ids
  */
 public void delete(String[] ids) {
  String hql = "delete from " + getEntityClass().getName()
    + " as o where o." + getIdName(getEntityClass()) + " in "
    + StringUtils.createBlock(ids);

  batchUpdate(hql);
 }

 public void delete(long[] ids) {
  String hql = "delete from " + getEntityClass().getName()
    + " as o where o." + getIdName(getEntityClass()) + " in "
    + StringUtils.createBlock(ids);
  batchUpdate(hql);
 }

 public List<T> findById(String[] ids){
  String hql = "from "+getEntityClass().getName()
    + " as o where o."+getIdName(getEntityClass())+" in "
    + StringUtils.createBlock(ids);
  return createHql(hql);
 }
 /**
  *
  * @param ids
  * @return
  */
 public String createBlock(long[] ids) {
  if (ids == null || ids.length == 0)
   return "('')";
  String blockStr = "(";
  for (int i = 0; i < ids.length - 1; i++) {
   blockStr += "'" + ids[i] + "',";
  }
  blockStr += "'" + ids[ids.length - 1] + "')";
  return blockStr;
 }

 /**
  * 批量更新
  * 用于审核,激活等操作
  * @param ids
  * @param property
  * @param value
  */
 public void update(String[] ids, String property, int value) {
  String hql = " update " + getEntityClass().getName() + " set "
    + property + "=" + value + " where "
    + getIdName(getEntityClass()) + " in "
    + StringUtils.createBlock(ids);
  batchUpdate(hql);
 }

 
 /**
  * map (key 为数据库字段 value 为修改的值) ids为空表示修改所有
  * 根据主建批量更新 支持多字段
  * 支持修改字段类型int long String byte
  */
 public void update(long[] ids, Map<String, Object> param) {
  if (param != null) {
   int index = 0;
   StringBuffer hql = new StringBuffer("update "
     + getEntityClass().getName() + " set ");
   Iterator<String> params = param.keySet().iterator();
   while (params.hasNext()) {
    String temp = params.next();
    hql.append(temp + "=? ,");
   }
   hql.deleteCharAt(hql.length() - 1);
   if (ids != null) {
    hql.append("where ");
    for (long id : ids) {
     hql
       .append(getIdName(getEntityClass()) + "=" + id
         + " and ");
    }
   }

   int end = hql.lastIndexOf("and");
   Query query = getSession().createQuery(
     end != -1 ? hql.substring(0, end) : hql.toString());

   params = param.keySet().iterator();
   while (params.hasNext()) {
    String temp = params.next();
    query.setParameter(index, param.get(temp));
    index++;
   }

   query.executeUpdate();
  }
 }
 
 
 
 
 
 
 
 
 
 
 
 /**
  * 获取最大SN序号
  * @return
  */
 public int selectMaxSn() {
  Criteria criteria = getSession().createCriteria(getEntityClass());
  criteria.setProjection(Projections.max("sn"));
  List list = criteria.list();
  if (list == null || list.get(0) == null)
   return 0;
  return (Integer) list.get(0);

 }

 /**
  * HQL分页查询数据
  * @param map 压入一些需要的参数
  * @return
  */
 public List findByPage(final Map map) {
  final int curPageNum = (Integer) map.get(PageConstant.CUR_PAGE_NUM);
  final int pageSize = (Integer) map.get(PageConstant.PAGE_SIZE);
  final String hql = getHql(map);
  final int startIndex = Page.getStartOfPage(curPageNum, pageSize);
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    List result = session.createQuery(hql).setFirstResult(
      startIndex).setMaxResults(pageSize).list();
    return result;
   }
  });
  return list;
 }

 /**
  * HQL分页 查询数据
  * @param map 压入一些需要的参数
  * @param hql 查询语句
  * @return
  */
 public List findByPage(final Map map, StringBuffer hql) {
  List paramList=new ArrayList();
  likeHql(hql, paramList, map);
  map.put(PageConstant.HQL, hql.toString());
  return findByPage(map);
 }

 /**
  * HQL查询所有记录的数量
  * @param map 压入需要的基本参数
  * @return
  */
 public long getRowCount(Map map) {
  final String hql = (String) map.get(PageConstant.HQL);
  long ret = (Long) getHibernateTemplate().execute(
    new HibernateCallback() {
     public Object doInHibernate(Session session)
       throws HibernateException, SQLException {
      return session.createQuery(hql).uniqueResult();
     }
    });
  return ret;
 }

 /**
  * HQL分页 查询数据
  * @param map 压入一些需要的参数
  * @param hql 查询语句
  * @return
  */
 public long getRowCount(Map map, StringBuffer hql) {
  likeHql(hql, null, map);
  map.put(PageConstant.HQL, hql.toString());
  return getRowCount(map);
 }

 /**
  * hql语句进行order by 排序
  * @param map
  * @return
  */
 public String getHql(final Map map) {
  final String orderByField = (String) map
    .get(PageConstant.ORDER_BY_FIELD);
  final String orderByDesc = (String) map.get(PageConstant.ORDER_BY_DESC);
  String hql = (String) map.get(PageConstant.HQL);
  if (ParamValidate.isNotEmpty(orderByField)
    && ParamValidate.isNotEmpty(orderByDesc)) {
   hql += (ParamValidate.isNotEmpty(orderByField) ? " order by "
     + orderByField : "")
     + " " + orderByDesc;
  }
  return hql;
 }

 /**
  * HQL查询分页语句
  * @param map
  * @param objects List 对象 需要传入参数防止注入时使用
  * @return
  */
 public List findByPage(final Map map, final List objects) {
  final int curPageNum = (Integer) map.get(PageConstant.CUR_PAGE_NUM);
  final int pageSize = (Integer) map.get(PageConstant.PAGE_SIZE);
  final String hql = getHql(map);
  final int startIndex = Page.getStartOfPage(curPageNum, pageSize);
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    Query query = createQuery(hql, objects);
    List result = query.setFirstResult(startIndex).setMaxResults(
      pageSize).list();
    return result;
   }
  });
  return list;
 }

 /**
  * 本地查询分页
  * @param map 压入需要的基本参数
  * @return
  */
 public List findBySQLPage(final Map map) {
  final int curPageNum = (Integer) map.get(PageConstant.CUR_PAGE_NUM);
  final int pageSize = (Integer) map.get(PageConstant.PAGE_SIZE);
  final String hql = getHql(map);
  final int startIndex = Page.getStartOfPage(curPageNum, pageSize);
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    List result = session.createSQLQuery(hql).setFirstResult(
      startIndex).setMaxResults(pageSize).list();
    return result;
   }
  });
  return list;
 }

 /**
  * 本地查询分页
  * @param map
  * @param query对象 
  * @return
  */

 public List findByPage(final Map map, final Query query) {
  final int curPageNum = (Integer) map.get(PageConstant.CUR_PAGE_NUM);
  final int pageSize = (Integer) map.get(PageConstant.PAGE_SIZE);
  final int startIndex = Page.getStartOfPage(curPageNum, pageSize);
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    List result = query.setFirstResult(startIndex).setMaxResults(
      pageSize).list();
    return result;
   }
  });
  return list;
 }

 /**
  * 本地查询分页
  * @param map 压入需要的基本参数
  * @param List 对象
  * @return
  */
 public List findBySQLPage(final Map map, final List objects) {
  final int curPageNum = (Integer) map.get(PageConstant.CUR_PAGE_NUM);
  final int pageSize = (Integer) map.get(PageConstant.PAGE_SIZE);
  final String hql = getHql(map);
  final int startIndex = Page.getStartOfPage(curPageNum, pageSize);
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    Query query = createSQLQuery(hql, objects);
    List result = query.setFirstResult(startIndex).setMaxResults(
      pageSize).list();
    return result;
   }
  });
  return list;
 }

 /**
  * 查询所有记录
  */
 public List<T> findAll() {
  return findAll(getEntityClass());
 }

 /**
  * 进行排序
  * @param hql
  * @param map
  * @return query 对象
  */
 public Query getHql(StringBuffer hql, final Map map) {
  map.put(PageConstant.HQL, hql.toString());
  return this.createQuery(getHql(map));
 }

 /**
  * 本地查询分页
  * @param map
  * @return
  */
 public long getRowSQLCount(Map map) {
  final String hql = (String) map.get(PageConstant.HQL);
  ;
  long ret = (Long) getHibernateTemplate().execute(
    new HibernateCallback() {
     public Object doInHibernate(Session session)
       throws HibernateException, SQLException {
      return session.createSQLQuery(hql).uniqueResult();
     }
    });
  return ret;
 }

 /**
  * 在构造函数中将泛型T.class赋给entityClass.
  */
 public HibernateEntityDao() {
  entityClass = com.framework.commons.utils.GenericsUtils
    .getSuperClassGenricType(getClass());
 }

 /**
  * 取得entityClass.JDK1.4不支持泛型的子类可以抛开Class<T> entityClass,重载此函数达到相同效果
  */
 protected Class<T> getEntityClass() {
  return entityClass;
 }

 /**
  * 获取全部对象,带排序参
  *
  * @see HibernateGenericDao#getAll(Class,String,boolean)
  */
 public List<T> findAll(String orderBy, boolean isAsc) {
  return findAll(getEntityClass(), orderBy, isAsc);
 }

 /**
  * 取得Entity的Criteria.
  *
  * @see HibernateGenericDao#createCriteria(Class,Criterion[])
  */
 public Criteria createCriteria(Criterion... criterions) {
  return createCriteria(getEntityClass(), criterions);
 }

 /**
  * 取得Entity的Criteria,带排序参
  *
  * @see HibernateGenericDao#createCriteria(Class,String,boolean,Criterion[])
  */
 public Criteria createCriteria(String orderBy, boolean isAsc,
   Criterion... criterions) {
  return createCriteria(getEntityClass(), orderBy, isAsc, criterions);
 }

 /**
  * 根据属名和属性查询对
  *
  * @return 符合条件的对象列
  * @see HibernateGenericDao#findBy(Class,String,Object)
  */
 public List<T> findBy(String propertyName, Object value) {
  return findBy(getEntityClass(), propertyName, value);
 }

 /**
  * 根据属名和属性查询对,带排序参
  *
  * @return 符合条件的对象列
  * @see HibernateGenericDao#findBy(Class,String,Object,String,boolean)
  */
 public List<T> findBy(String propertyName, Object value, String orderBy,
   boolean isAsc) {
  return findBy(getEntityClass(), propertyName, value, orderBy, isAsc);
 }

 /**
  * 根据属名和属性查询单个对
  *
  * @return 符合条件的唯对象 or null
  * @see HibernateGenericDao#findUniqueBy(Class,String,Object)
  */
 public T findUniqueBy(String propertyName, Object value) {
  return findUniqueBy(getEntityClass(), propertyName, value);
 }

 /**
  * 判断对象某些属的值在数据库中唯一.
  *
  * @param uniquePropertyNames
  *            在POJO里不能重复的属列,以号分割"name,loginid,password"
  * @see HibernateGenericDao#isUnique(Class,Object,String)
  */
 public boolean isUnique(Object entity, String uniquePropertyNames) {
  return isUnique(getEntityClass(), entity, uniquePropertyNames);
 }

 /**
  * hibernate批量更新--(删除/修改)
  *
  * @param hql
  */
 public void batchUpdate(final String hql) {
  getHibernateTemplate().execute(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    session.createQuery(hql).executeUpdate();
    return null;
   }
  });
 }

 /**
  * 任意执行HQL
  *
  * @return 符合条件的唯对象 or null
  * @author jichun
  */
 public List createHql(final String hql) {
  List list = getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session session)
     throws HibernateException, SQLException {
    List result = session.createQuery(hql).list();
    return result;
   }
  });
  return list;

 }

 /**
  * 字段like后HQL语句
  * @param buffer
  * @param list
  * @param map
  */
 public List  likeHql(StringBuffer buffer, List list, Map map) {
  if (ParamValidate.isEmpty(list))
   list = new ArrayList();
  // buffer
  String group = null;
  String order=null;
  if (buffer.lastIndexOf("group") != -1) {
   group = buffer.substring(buffer.lastIndexOf("group"), buffer
     .length());
   buffer = buffer.replace(buffer.lastIndexOf("group"), buffer
     .length(), "");
  }

  if (buffer.lastIndexOf("order") != -1) {
   group = buffer.substring(buffer.lastIndexOf("order"), buffer
     .length());
   buffer = buffer.replace(buffer.lastIndexOf("order"), buffer
     .length(), "");
  }
  
  String searchField = (String) map.get(PageConstant.SEARCH_FIELD);
  String searchValue = (String) map.get(PageConstant.SEARCH_VALUE);
  if (ParamValidate.isNotEmpty(searchField)) {
   buffer.append(" and " + searchField + " like " + " (  ? )  ");
   list.add(ParamValidate.isEmpty(searchValue) ? "%%": "%" + searchValue
     + "%");
  }
  if (group != null)
   buffer.append(" "+group+" ");
  
  if (order!=null)
   buffer.append(" "+order+" ");

  return list;
 }

 /**
  * 本地分页查询语句 支持列表控件搜索
  * @return
  */
 public List findBySqlPage(Map map, List paramList, StringBuffer hql) {
  likeHql(hql, paramList, map);
  map.put(PageConstant.HQL, hql.toString());
  return findBySQLPage(map, paramList);
 }

 /**
  * 本地查询方法 查找列表总数
  * @param hql
  * @param values
  * @return
  */
 public long getRowSQLCount(StringBuffer hql, List<Object> paramList, Map map) {
  likeHql(hql, paramList, map);
  Query query = createSQLQuery(hql.toString(), paramList);
  long num = ((BigInteger) query.uniqueResult()).longValue();
  if (paramList != null)
   paramList.clear();
  return num;
 }

 /**
  * 本地查询方法 查找列表总数
  * @param hql
  * @param values
  * @return
  */
 public long getRowCount(StringBuffer hql, List<Object> paramList, Map map) {
  paramList=likeHql(hql, paramList, map);
  Query query = createQuery(hql.toString(), paramList);
  long num = (Long) query.uniqueResult();
  if (paramList != null)
   paramList.clear();
  return num;
 }
 
 
 /**
  * 本地分页查询语句 支持列表控件搜索
  * @return
  */
 public List findByPage(Map map, List paramList, StringBuffer hql) {
  paramList=likeHql(hql, paramList, map);
  map.put(PageConstant.HQL, hql.toString());
  return findByPage(map, paramList);
 }

 /**
  * 本地查询方法 查找列表总数
  * @param hql
  * @param values
  * @return
  */
 public long getRowSQLCount(String hql, List<Object> values) {
  Query query = createSQLQuery(hql, values);
  long num = ((BigInteger) query.uniqueResult()).longValue();
  if (values != null)
   values.clear();
  return num;
 }
}

你可能感兴趣的:(SHS框架下的basedao 很有用的 核心类)