HibernateDao.java

/**java

 * Copyright (c) 2005-2010 springside.org.cnspring

 *apache

 * Licensed under the Apache License, Version 2.0 (the "License");數組

 * session

 * $Id: HibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $ide

 */函數

package com.dao.hibernate;ui


import java.io.Serializable;spa

import java.util.ArrayList;hibernate

import java.util.List;

import java.util.Map;


import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.math.NumberUtils;

import org.hibernate.Criteria;

import org.hibernate.Query;

import org.hibernate.SessionFactory;

import org.hibernate.criterion.CriteriaSpecification;

import org.hibernate.criterion.Criterion;

import org.hibernate.criterion.Disjunction;

import org.hibernate.criterion.MatchMode;

import org.hibernate.criterion.Order;

import org.hibernate.criterion.Projection;

import org.hibernate.criterion.Projections;

import org.hibernate.criterion.Restrictions;

import org.hibernate.impl.CriteriaImpl;

import org.hibernate.transform.ResultTransformer;

import org.springframework.util.Assert;


import com.dao.hibernate.PropertyFilter.MatchType;

import com.utils.ReflectionUtils;


/**

 * 封裝SpringSide擴展功能的Hibernat DAO泛型基類.

 * 

 * 擴展功能包括分頁查詢,按屬性過濾條件列表查詢. 可在Service層直接使用,也能夠擴展泛型DAO子類使用,見兩個構造函數的註釋.

 * 

 * @param <T>

 *            DAO操做的對象類型

 * @param <PK>

 *            主鍵類型

 * 

 * @author calvin

 */

public class HibernateDao<T, PK extends Serializable> extends

SimpleHibernateDao<T, PK> {

/**

* 用於Dao層子類的構造函數. 經過子類的泛型定義取得對象類型Class. eg. public class UserDao extends

* HibernateDao<User, Long>{ }

*/

public HibernateDao() {

super();

}


/**

* 用於省略Dao層, Service層直接使用通用HibernateDao的構造函數. 在構造函數中定義對象類型Class. eg.

* HibernateDao<User, Long> userDao = new HibernateDao<User,

* Long>(sessionFactory, User.class);

*/

public HibernateDao(final SessionFactory sessionFactory,

final Class<T> entityClass) {

super(sessionFactory, entityClass);

}


// -- 分頁查詢函數 --//


/**

* 分頁獲取所有對象.

*/

public Page<T> getAll(final Page<T> page) {

return findPage(page);

}


/**

* 按HQL分頁查詢.

* @param page

*            分頁參數. 注意不支持其中的orderBy參數.

* @param hql

*            hql語句.

* @param values

*            數量可變的查詢參數,按順序綁定.

* @return 分頁查詢結果, 附帶結果列表及全部查詢輸入參數.

*/

public Page<T> findPage(final Page<T> page, final String hql,

final Object... values) {

Assert.notNull(page, "page不能爲空");


Query q = createQuery(hql, values);


if (page.isAutoCount()) {

long totalCount = countHqlResult(hql, values);

page.setTotalCount(totalCount);

}


setPageParameterToQuery(q, page);


List result = q.list();

page.setResult(result);

return page;

}


/**

* 按HQL分頁查詢.

* @param page

*            分頁參數. 注意不支持其中的orderBy參數.

* @param hql

*            hql語句.

* @param values

*            命名參數,按名稱綁定.

* @return 分頁查詢結果, 附帶結果列表及全部查詢輸入參數.

*/

@SuppressWarnings("unchecked")

public Page<T> findPage(final Page<T> page, final String hql,

final Map<String, ?> values) {

Assert.notNull(page, "page不能爲空");


Query q = createQuery(hql, values);


if (page.isAutoCount()) {

long totalCount = countHqlResult(hql, values);

page.setTotalCount(totalCount);

}


setPageParameterToQuery(q, page);


List result = q.list();

page.setResult(result);

return page;

}


/**

* 按Criteria分頁查詢.

* @param page

*            分頁參數.

* @param criterions

*            數量可變的Criterion.

* @return 分頁查詢結果.附帶結果列表及全部查詢輸入參數.

*/

@SuppressWarnings("unchecked")

public Page<T> findPage(final Page<T> page, final Criterion... criterions) {

Assert.notNull(page, "page不能爲空");


Criteria c = createCriteria(criterions);


if (page.isAutoCount()) {

long totalCount = countCriteriaResult(c);

page.setTotalCount(totalCount);

}

if(page.getPageNo() > page.getTotalPages()) {

page.setPageNo(NumberUtils.toInt(Long.toString(page.getTotalPages())));

}

setPageParameterToCriteria(c, page);


List result = c.list();

page.setResult(result);

return page;

}


/**

* 設置分頁參數到Query對象,輔助函數.

*/

protected Query setPageParameterToQuery(final Query q, final Page<T> page) {


Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");


// hibernate的firstResult的序號從0開始

q.setFirstResult(page.getFirst() - 1);

q.setMaxResults(page.getPageSize());

return q;

}


/**

* 設置分頁參數到Criteria對象,輔助函數.

*/

protected Criteria setPageParameterToCriteria(final Criteria c,

final Page<T> page) {


Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");


// hibernate的firstResult的序號從0開始

c.setFirstResult(page.getFirst() - 1);

c.setMaxResults(page.getPageSize());


if (page.isOrderBySetted()) {

String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');

String[] orderArray = StringUtils.split(page.getOrder(), ',');


Assert.isTrue(orderByArray.length == orderArray.length,

"分頁多重排序參數中,排序字段與排序方向的個數不相等");


for (int i = 0; i < orderByArray.length; i++) {

if (Page.ASC.equals(orderArray[i])) {

c.addOrder(Order.asc(orderByArray[i]));

} else {

c.addOrder(Order.desc(orderByArray[i]));

}

}

}

return c;

}


/**

* 執行count查詢得到本次Hql查詢所能得到的對象總數.

* 本函數只能自動處理簡單的hql語句,複雜的hql查詢請另行編寫count語句查詢.

*/

protected long countHqlResult(final String hql, final Object... values) {

String countHql = prepareCountHql(hql);


try {

Long count = findUnique(countHql, values);

return count;

} catch (Exception e) {

throw new RuntimeException("hql can't be auto count, hql is:"

+ countHql, e);

}

}


/**

* 執行count查詢得到本次Hql查詢所能得到的對象總數.

* 本函數只能自動處理簡單的hql語句,複雜的hql查詢請另行編寫count語句查詢.

*/

protected long countHqlResult(final String hql, final Map<String, ?> values) {

String countHql = prepareCountHql(hql);


try {

Long count = findUnique(countHql, values);

return count;

} catch (Exception e) {

throw new RuntimeException("hql can't be auto count, hql is:"

+ countHql, e);

}

}


private String prepareCountHql(String orgHql) {

String fromHql = orgHql;

// select子句與order by子句會影響count查詢,進行簡單的排除.

fromHql = "from " + StringUtils.substringAfter(fromHql, "from");

fromHql = StringUtils.substringBefore(fromHql, "order by");


String countHql = "select count(*) " + fromHql;

return countHql;

}


/**

* 執行count查詢得到本次Criteria查詢所能得到的對象總數.

*/

@SuppressWarnings("unchecked")

protected long countCriteriaResult(final Criteria c) {

CriteriaImpl impl = (CriteriaImpl) c;


// 先把Projection、ResultTransformer、OrderBy取出來,清空三者後再執行Count操做

Projection projection = impl.getProjection();

ResultTransformer transformer = impl.getResultTransformer();


List<CriteriaImpl.OrderEntry> orderEntries = null;

try {

orderEntries = (List) ReflectionUtils.getFieldValue(impl,

"orderEntries");

ReflectionUtils

.setFieldValue(impl, "orderEntries", new ArrayList());

} catch (Exception e) {

logger.error("不可能拋出的異常:{}", e.getMessage());

}


// 執行Count查詢

Long totalCountObject = Long.parseLong(c

.setProjection(Projections.rowCount()).uniqueResult()

.toString());

long totalCount = (totalCountObject != null) ? totalCountObject : 0;


// 將以前的Projection,ResultTransformer和OrderBy條件從新設回去

c.setProjection(projection);


if (projection == null) {

c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

}

if (transformer != null) {

c.setResultTransformer(transformer);

}

try {

ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);

} catch (Exception e) {

logger.error("不可能拋出的異常:{}", e.getMessage());

}


return totalCount;

}


// -- 屬性過濾條件(PropertyFilter)查詢函數 --//


/**

* 按屬性查找對象列表,支持多種匹配方式.

* @param matchType

*            匹配方式,目前支持的取值見PropertyFilter的MatcheType enum.

*/

public List<T> findBy(final String propertyName, final Object value,

final MatchType matchType) {

Criterion criterion = buildCriterion(propertyName, value, matchType);

return find(criterion);

}


/**

* 按屬性過濾條件列表查找對象列表.

*/

public List<T> find(List<PropertyFilter> filters) {

Criterion[] criterions = buildCriterionByPropertyFilter(filters);

return find(criterions);

}


/**

* 按屬性過濾條件列表分頁查找對象.

*/

public Page<T> findPage(final Page<T> page,

final List<PropertyFilter> filters) {

Criterion[] criterions = buildCriterionByPropertyFilter(filters);

return findPage(page, criterions);

}


/**

* 按屬性條件參數建立Criterion,輔助函數.

*/

protected Criterion buildCriterion(final String propertyName,

final Object propertyValue, final MatchType matchType) {

Assert.hasText(propertyName, "propertyName不能爲空");

Criterion criterion = null;

// 根據MatchType構造criterion

switch (matchType) {

case EQ:

criterion = Restrictions.eq(propertyName, propertyValue);

break;

case LIKE:

criterion = Restrictions.like(propertyName, (String) propertyValue,

MatchMode.ANYWHERE);

break;


case LE:

criterion = Restrictions.le(propertyName, propertyValue);

break;

case LT:

criterion = Restrictions.lt(propertyName, propertyValue);

break;

case GE:

criterion = Restrictions.ge(propertyName, propertyValue);

break;

case GT:

criterion = Restrictions.gt(propertyName, propertyValue);

}

return criterion;

}


/**

* 按屬性條件列表建立Criterion數組,輔助函數.

*/

protected Criterion[] buildCriterionByPropertyFilter(

final List<PropertyFilter> filters) {

List<Criterion> criterionList = new ArrayList<Criterion>();

for (PropertyFilter filter : filters) {

if (!filter.hasMultiProperties()) { // 只有一個屬性須要比較的狀況.

Criterion criterion = buildCriterion(filter.getPropertyName(),

filter.getMatchValue(), filter.getMatchType());

criterionList.add(criterion);

} else {// 包含多個屬性須要比較的狀況,進行or處理.

Disjunction disjunction = Restrictions.disjunction();

for (String param : filter.getPropertyNames()) {

Criterion criterion = buildCriterion(param,

filter.getMatchValue(), filter.getMatchType());

disjunction.add(criterion);

}

criterionList.add(disjunction);

}

}

return criterionList.toArray(new Criterion[criterionList.size()]);

}

}

相關文章
相關標籤/搜索