hibernate 基礎dao類實現2

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;
 }
}

發佈了29 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章