package com.xq9527.util.dao;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.xwork.StringUtils;
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.xq9527.util.vo.DataSet;
import com.xq9527.util.vo.Page;
import com.xq9527.util.vo.PageInfo;
/**
* 实体基类
* Create at 2012-6-6 下午01:45:07
* @param <T> 实体类
* @param <PK> 主键类型
*/
public class HibernateBaseDao<T, PK extends Serializable> extends HibernateGenericDao<T, PK> {
public HibernateBaseDao() {
super();
}
/**
* 构造函数
* @param sessionFactory 事务
* @param entityClass 实体类
*/
public HibernateBaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
super(sessionFactory, entityClass);
}
//************************************通用方法****************************************
/**
* sql查询件数
* @param sql
* @return
* int 返回类型
*/
protected int countSqlResult(final String sql) {
String countSql = "select count(*) from ("+sql+")";
try {
int count = ((BigDecimal) this.getSession().createSQLQuery(countSql).uniqueResult()).intValue();
return count;
} catch (Exception e) {
throw new RuntimeException("hql can't be auto count, sql is:" + countSql, e);
}
}
//-- 分页查询函数 --//
public Page<T> getAll(final Page<T> page) {
return findPage(page);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
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);
}
setPageParameter(q, page);
List result = q.list();
page.setResult(result);
return page;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Page<T> findPage(final Page<T> page, final String hql, final Map<String, Object> values) {
Assert.notNull(page, "page不能为空");
Query q = createQuery(hql, values);
if (page.isAutoCount()) {
long totalCount = countHqlResult(hql, values);
page.setTotalCount(totalCount);
}
setPageParameter(q, page);
List result = q.list();
page.setResult(result);
return page;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
Assert.notNull(page, "page不能为空");
Criteria c = createCriteria(criterions);
if (page.isAutoCount()) {
int totalCount = countCriteriaResult(c);
page.setTotalCount(totalCount);
}
setPageParameter(c, page);
List result = c.list();
page.setResult(result);
return page;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Page<T> findByCriteria(final Page<T> page, final Criteria criteria) {
Assert.notNull(page, "page不能为空");
if (page.isAutoCount()) {
int totalCount = countCriteriaResult(criteria);
page.setTotalCount(totalCount);
}
setPageParameter(criteria, page);
List result = criteria.list();
page.setResult(result);
return page;
}
protected Query setPageParameter(final Query q, final Page<T> page) {
//hibernate的firstResult的序号从0开始
q.setFirstResult(page.getFirst() - 1);
q.setMaxResults(page.getPageSize());
return q;
}
protected Criteria setPageParameter(final Criteria c, final Page<T> page) {
//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;
}
protected long countHqlResult(final String hql, final Object... values) {
String fromHql = hql;
//select子句与order by子句会影响count查询,进行简单的排除.
fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
fromHql = StringUtils.substringBefore(fromHql, "order by");
String countHql = "select count(o) " + fromHql;
try {
Long count = findUnique(countHql, values);
return count;
} catch (Exception e) {
throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
}
}
protected long countHqlResult(final String hql, final Map<String, Object> values) {
String fromHql = hql;
//select子句与order by子句会影响count查询,进行简单的排除.
fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
fromHql = StringUtils.substringBefore(fromHql, "order by");
String countHql = "select count(o) " + fromHql;
try {
Long count = findUnique(countHql, values);
return count;
} catch (Exception e) {
throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected int 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查询
int totalCount = ((Long) c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
// 将之前的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)查询函数 --//
public List<T> findBy(final String propertyName, final Object value, final PropertyFilter.MatchType matchType) {
Criterion criterion = buildPropertyFilterCriterion(propertyName, value, matchType);
return find(criterion);
}
public List<T> find(List<PropertyFilter> filters) {
Criterion[] criterions = buildPropertyFilterCriterions(filters);
return find(criterions);
}
public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
Criterion[] criterions = buildPropertyFilterCriterions(filters);
return findPage(page, criterions);
}
protected Criterion[] buildPropertyFilterCriterions(final List<PropertyFilter> filters) {