package com.test.main.core.dao; import java.math.BigDecimal; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import com.test.main.core.web.Page; @Repository("hibernateGenericDao") public class HibernateGenericDao<T> extends HibernateDaoSupport { @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } /** * 根据hql查询,直接使用HibernateTemplate的find函数. * * @param values:可变参数 */ @SuppressWarnings("unchecked") public List<T> find(String hql, Object... values) throws DataAccessException { Assert.hasText(hql); return getHibernateTemplate().find(hql, values); } /** * 按HQL分页查询. * * @param page 分页参数. 注意不支持其中的orderBy参数. * @param hql hql语句. * @param values 数量可变的查询参数,按顺序绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ @SuppressWarnings("unchecked") 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, Map paramMap) { Assert.notNull(page, "page不能为空"); Query q = createQuery(hql, paramMap); if (page.isAutoCount()) { long totalCount = countHqlResult(hql, paramMap); page.setTotalCount(totalCount); } setPageParameterToQuery(q, page); List result = q.list(); page.setResult(result); return page; } /** * 按SQL分页查询. * * @param page 分页参数. 注意不支持其中的orderBy参数. * @param hql hql语句. * @param values 数量可变的查询参数,按顺序绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ @SuppressWarnings("unchecked") public Page findPageBySql(final Page page, final String sql, final Object... values) { Assert.notNull(page, "page不能为空"); Query q = createQuerySQL(sql, values); if (page.isAutoCount()) { long totalCount = countSqlResult(sql, values); page.setTotalCount(totalCount); } q.setFirstResult(page.getFirst() - 1); q.setMaxResults(page.getPageSize()); List result = q.list(); page.setResult(result); return page; } //重载方法 返回Map 对象集合 @SuppressWarnings("unchecked") public Page findPageBySql(final Page page, final String sql,boolean isReturnMap, final Object... values) { Assert.notNull(page, "page不能为空"); Query q = createQuerySQL(sql, values); if (page.isAutoCount()) { long totalCount = countSqlResult(sql, values); page.setTotalCount(totalCount); } q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); q.setFirstResult(page.getFirst() - 1); q.setMaxResults(page.getPageSize()); List result = q.list(); page.setResult(result); return page; } /** * 根据查询SQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 数量可变的参数,按顺序绑定. */ public Query createQuerySQL(final String sql, final Object... values) { Assert.hasText(sql, "sql不能为空"); Query query = getSession().createSQLQuery(sql); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * 执行count查询获得本次sql查询所能获得的对象总数. * * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询. */ protected long countSqlResult(final String hql, final Object... values) { String countHql = prepareCountSQL(hql); try { Long count = findUniqueSQL(countHql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 数量可变的参数,按顺序绑定. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param paramMap 过滤条件 */ public Query createQuery(final String queryString, final Map<String,?> paramMap) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createQuery(queryString); if (paramMap != null) { Iterator<String> it= paramMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); Object value=paramMap.get(key); if(value instanceof Object[]){ query.setParameterList(key, (Object[])value); }else{ query.setParameter(key, value); } } } return query; } /** * 执行count查询获得本次SQL查询所能获得的对象总数. * * 本函数只能自动处理简单的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查询获得本次SQL查询所能获得的对象总数. * * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询. */ protected long countHqlResult(final String hql, final Map<String, Object> paramMap) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql, paramMap); 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; } private String prepareCountSQL(String orgSql) { String countSql = "select count(*) from (" + orgSql+") tt"; return countSql; } /** * 按SQL查询唯一对象. * * @param values 数量可变的参数,按顺序绑定. */ public Long findUniqueSQL(final String sql, final Object... values) { return ((BigDecimal) createQuerySQL(sql, values).uniqueResult()).longValue(); } /** * 按HQL查询唯一对象. * * @param values 数量可变的参数,按顺序绑定. */ public Long findUnique(final String hql, final Object... values) { return (Long) createQuery(hql, values).uniqueResult(); } /** * 按HQL查询唯一对象. * * @param paramMap 数量可变的参数,按顺序绑定. */ public Long findUnique(final String hql, final Map<String,Object> paramMap) { return (Long) createQuery(hql, paramMap).uniqueResult(); } /** * 设置分页参数到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; } }package com.test.main.core.dao; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.springframework.dao.DataAccessException; import com.test.main.core.web.Page; public interface BaseDao<T, PK extends Serializable> { /** * 清除所有对象缓存 */ public void clear() throws DataAccessException; /** * 持久化多个实体。 * * @param entities :处于临时状态的实体的集合。 * @throws DataAccessException */ void create(Collection<T> entities) throws DataAccessException; /** * 持久化一个实体。 * * @param entity :处于临时状态的实体。 * @throws DataAccessException */ void create(T entity) throws DataAccessException; /** * 持久化或者更新多个实体。 * * @param entities :处于临时或者持久化状态的实体的集合。 * @throws DataAccessException */ void createOrUpdate(Collection<T> entities) throws DataAccessException; /** * 持久化或者更新实体。 * * @param entity :处于临时或者持久化状态的实体。 * @throws DataAccessException */ void createOrUpdate(T entity) throws DataAccessException; /** * 删除多个持久化的实体。 * * @param entities :处于持久化状态的实体的集合。 * @throws DataAccessException */ void delete(Collection<T> entities) throws DataAccessException; /** * 删除一个持久化的实体。 * * @param entity :处于持久化状态的实体。 * @throws DataAccessException */ void delete(T entity) throws DataAccessException; /** * 根据ID移除对象. */ public void deleteById(PK id) throws DataAccessException; /** * 消除与 Hibernate Session 的关联 */ public void evit(T entity) throws DataAccessException; /** * 执行本地sql语句获得标量数值列表 返回Object数组 */ @SuppressWarnings("unchecked") public List executeNativeSql(String sql) throws DataAccessException; /** * 执行hql语句 * * @param hql * @throws DataAccessException */ public void executeUpdate(String hql) throws DataAccessException; /** * 执行本地sql语句获得标量数值列表 返回实体对象 */ public List<T> executeNativeSqlToClass(String sql) throws DataAccessException; /** * 根据hql查询,直接使用HibernateTemplate的find函数. */ @SuppressWarnings("unchecked") public List<T> find(String hql, Object... values) throws DataAccessException; public void flush(); /** * 根据ID获取对象,如果对象不存在,返回 null */ public T get(PK id) throws DataAccessException; /** * 获取全部对象 */ public List<T> getAll() throws DataAccessException; /** * 获取全部对象,带排序字段与升降序参数. */ public List<T> getAll(String orderBy, boolean isAsc) throws DataAccessException; /** * 根据ID获取对象,如果对象不存在,抛出异常. */ public T load(PK id) throws DataAccessException; /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 命名参数,按名称绑定. */ public Query createQuery(final String queryString, final Map<String, ?> values); /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 数量可变的参数,按顺序绑定. */ public Query createQuery(final String queryString, final Object... values); /** * 根据Criterion条件创建Criteria. 与find()函数可进行更加灵活的操作. * * @param criterions 数量可变的Criterion. */ public Criteria createCriteria(final Criterion... criterions); /** * 保存处于游离状态的多个实体,更新后实体对象仍然处于游离状态。 * * @param entities :处于游离状态的实体的集合。 * @throws DataAccessException */ void merge(Collection<T> entities) throws DataAccessException; /** * 更新处于游离状态的实体,更新后实体对象仍然处于游离状态。 * * @param entity :处于游离状态的实体。 * @throws DataAccessException */ void merge(T entity) throws DataAccessException; /** * 分页查询 * * @param page :分页对象 * @param hql :hql语句 * @param values :参数值 * @return page:对象 * @throws DataAccessException */ Page<T> findPage(Page<T> page, String hql, Object... values) throws DataAccessException; Page<T> findPage(Page<T> page, String hql, Map<String, Object> paramMap) throws DataAccessException; /** * 分页查询 * * @param page :分页对象 * @param sql :hql语句 * @param values :参数值 * @return page:对象 * @throws DataAccessException */ Page<T> findPageBySQL(Page<T> page, String sql, Object... values) throws DataAccessException; /** * 更新多个实体。 * * @param entities :处于持久化状态的实体的集合。 * @throws DataAccessException */ void update(Collection<T> entities) throws DataAccessException; /** * 更新实体。 * * @param entity :处于持久化状态的实体。 * @throws DataAccessException */ void update(T entity) throws DataAccessException; /** * 按Criteria查询对象列表. * * @param criterions 数量可变的Criterion. */ List<T> find(final Criterion... criterions); /** * 按属性过滤条件列表查找对象列表. */ List<T> find(List<PropertyFilter> filters); List<T> find(List<PropertyFilter> filters,List<Order> orders); List<T> find(HashMap<String, String> aliasMap, List<PropertyFilter> filters); /** * 执行count查询获得本次Criteria查询所能获得的对象总数. */ long countCriteriaResult(final Criteria c); /** * 按Criteria分页查询. * * @param page 分页参数. * @param criterions 数量可变的Criterion. * * @return 分页查询结果.附带结果列表及所有查询输入参数. */ @SuppressWarnings("unchecked") public Page<T> findPage(final Page<T> page, final Criterion... criterions); /** * 按属性过滤条件列表分页查找对象. */ Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters); }
package com.test.main.core.dao; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; 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.DetachedCriteria; 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.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.util.Assert; import com.test.main.core.dao.PropertyFilter.MatchType; import com.test.main.core.web.Page; import com.test.main.util.ReflectionUtils; @Scope("prototype") public class BaseDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport implements BaseDao<T, PK> { @Autowired private HibernateGenericDao<T> hibernateGenericDao; protected final Logger logger = LogManager.getLogger(BaseDaoHibernate.class); protected Class<T> entityClass; public BaseDaoHibernate() { } public BaseDaoHibernate(Class<T> entityClass) { this.entityClass = entityClass; } public void clear() throws DataAccessException { getHibernateTemplate().clear(); } public void create(Collection<T> entities) throws DataAccessException { if (entities != null && entities.size() > 0) { Iterator<T> it = entities.iterator(); for (T e = null; it.hasNext();) { e = it.next(); create(e); } } } public void create(T entity) throws DataAccessException { getHibernateTemplate().save(entity); } public void createOrUpdate(Collection<T> entities) throws DataAccessException { if (entities != null && entities.size() > 0) { Iterator<T> it = entities.iterator(); for (T e = null; it.hasNext();) { e = it.next(); createOrUpdate(e); } } } public void createOrUpdate(T entity) throws DataAccessException { getHibernateTemplate().saveOrUpdate(entity); } public void delete(Collection<T> entities) throws DataAccessException { if (entities != null && entities.size() > 0) { Iterator<T> it = entities.iterator(); for (T e = null; it.hasNext();) { e = it.next(); delete(e); } } } public void delete(T entity) throws DataAccessException { super.getHibernateTemplate().delete(entity); } public void deleteById(PK id) throws DataAccessException { delete(get(id)); } public void evit(T entity) throws DataAccessException { getHibernateTemplate().evict(entity); } /** * 执行本地sql语句获得标量数值列表 返回Object数组 */ @SuppressWarnings("unchecked") public List executeNativeSql(String sql) throws DataAccessException { return getSession().createSQLQuery(sql).list(); } @SuppressWarnings("unchecked") public void executeUpdate(String hql) throws DataAccessException { getSession().createQuery(hql).executeUpdate(); } /** * 执行本地sql语句获得标量数值列表 返回实体对象 */ @SuppressWarnings("unchecked") public List<T> executeNativeSqlToClass(String sql) throws DataAccessException { return getSession().createSQLQuery(sql).addEntity(this.entityClass).list(); } @SuppressWarnings("unchecked") public List<T> find(String hql, Object... values) throws DataAccessException { return hibernateGenericDao.find(hql, values); } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 命名参数,按名称绑定. */ public Query createQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString不能为空"); Query query = hibernateGenericDao.createQuery(queryString,values); return query; } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values 数量可变的参数,按顺序绑定. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * 根据Criterion条件创建Criteria. 与find()函数可进行更加灵活的操作. * * @param criterions 数量可变的Criterion. */ public Criteria createCriteria(final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } public void flush() throws DataAccessException { getHibernateTemplate().flush(); } public T get(PK id) throws DataAccessException { return (T) getHibernateTemplate().get(entityClass, id); } public List<T> getAll() throws DataAccessException { return (List<T>) (getHibernateTemplate().loadAll(entityClass)); } @SuppressWarnings("unchecked") public List<T> getAll(String orderBy, boolean isAsc) throws DataAccessException { Assert.hasText(orderBy); if (isAsc) return getHibernateTemplate().findByCriteria( DetachedCriteria.forClass(entityClass).addOrder(Order.asc(orderBy))); else return getHibernateTemplate().findByCriteria( DetachedCriteria.forClass(entityClass).addOrder(Order.desc(orderBy))); } public T load(PK id) throws DataAccessException { return (T) getHibernateTemplate().load(entityClass, id); } public void merge(Collection<T> entities) throws DataAccessException { if (entities != null && entities.size() > 0) { Iterator<T> it = entities.iterator(); for (T e = null; it.hasNext();) { e = it.next(); merge(e); } } } public void merge(T entity) throws DataAccessException { super.getHibernateTemplate().merge(entity); } public Page<T> findPage(Page<T> page, String hql, Object... values) throws DataAccessException { return hibernateGenericDao.findPage(page, hql, values); } public Page<T> findPage(Page<T> page, String hql, Map<String,Object> paramMap) throws DataAccessException { return hibernateGenericDao.findPage(page, hql, paramMap); } @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } public void update(Collection<T> entities) throws DataAccessException { if (entities != null && entities.size() > 0) { Iterator<T> it = entities.iterator(); for (T e = null; it.hasNext();) { e = it.next(); update(e); } } } public void update(T entity) throws DataAccessException { getHibernateTemplate().update(entity); } /** * 按Criteria查询对象列表. * * @param criterions 数量可变的Criterion. */ @SuppressWarnings("unchecked") public List<T> find(final Criterion... criterions) { DetachedCriteria criteria = DetachedCriteria.forClass(entityClass); for (Criterion c : criterions) { criteria.add(c); } return getHibernateTemplate().findByCriteria(criteria); } /** * 按Criteria查询对象列表. * * @param criterions 数量可变的Criterion. */ @SuppressWarnings("unchecked") public List<T> find(List<Order> orders,final Criterion... criterions) { DetachedCriteria criteria = DetachedCriteria.forClass(entityClass); for (Criterion c : criterions) { criteria.add(c); } for (Order order : orders) { criteria.addOrder(order); } return getHibernateTemplate().findByCriteria(criteria); } /** * 按Criteria查询对象列表. * * @param criterions 数量可变的Criterion. */ @SuppressWarnings("unchecked") public List<T> find(final HashMap<String, String> aliasMap, final Criterion... criterions) { DetachedCriteria criteria = DetachedCriteria.forClass(entityClass); if (aliasMap != null) { Iterator<String> iterator = aliasMap.keySet().iterator(); while (iterator.hasNext()) { String alias = (String) iterator.next(); criteria.createAlias(alias, aliasMap.get(alias)); } } for (Criterion c : criterions) { criteria.add(c); } return getHibernateTemplate().findByCriteria(criteria); } /** * 按属性过滤条件列表查找对象列表. */ public List<T> find(List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return find(criterions); } /** * 按属性过滤条件列表查找对象列表.待排序 */ public List<T> find(List<PropertyFilter> filters,List<Order> orders) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return find(orders,criterions); } /** * 按属性过滤条件列表查找对象列表. */ public List<T> find(HashMap<String, String> aliasMap, List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return find(aliasMap, 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()]); } /** * 执行count查询获得本次Criteria查询所能获得的对象总数. */ @SuppressWarnings("unchecked") public 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); } // 执行Count查询 Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult(); 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); } return totalCount; } /** * 按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); } setPageParameterToCriteria(c, page); List result = c.list(); page.setResult(result); return page; } /** * 设置分页参数到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; } /** * 按属性过滤条件列表分页查找对象. */ public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return findPage(page, criterions); } @SuppressWarnings("unchecked") public Page<T> findPageBySQL(Page<T> page, String sql, Object... values) throws DataAccessException { return hibernateGenericDao.findPageBySql(page, sql, values); } @SuppressWarnings("unchecked") public Page<T> findPageBySQL(Page<T> page, String sql,boolean isReturnMap, Object... values) throws DataAccessException { return hibernateGenericDao.findPageBySql(page, sql,isReturnMap, values); } }
应用例子:
package com.test.crawler.initcrawler.dao; import java.util.List; import com.test.crawler.core.dao.BaseDao; import com.test.crawler.core.dao.Page; import com.test.crawler.initcrawler.entity.UrlFilter; public interface UrlFilterDao extends BaseDao<UrlFilter, String> { /** * 根据种子节点与状态,查询种子入口过滤网址. * @param note 节点 * @param stauts 状态 * @return */ public List<UrlFilter> findUrlFilterByNoteAndStruts(String note,String status); /** * 根据节点与状态,查询过滤网址 * @param note * @param stauts * @param type * @return */ public List<UrlFilter> findFilterByType(String note,String stauts,String type);
package com.test.crawler.initcrawler.dao.imp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.test.crawler.core.dao.BaseDaoHibernate; import com.test.crawler.core.dao.Page; import com.test.crawler.initcrawler.dao.UrlFilterDao; import com.test.crawler.initcrawler.entity.UrlFilter; @Repository("urlFilterDao") public class UrlFilterDaoImp extends BaseDaoHibernate<UrlFilter,String> implements UrlFilterDao { @Autowired private JdbcTemplate jdbcTemplate; public UrlFilterDaoImp() { super(UrlFilter.class); } public List<UrlFilter> findUrlFilterByNoteAndStruts(String note, String status) { String hql = "FROM UrlFilter t WHERE t.node=? and t.status=?"; return this.find(hql, note,status); } public List<UrlFilter> findFilterByType(String note,String stauts,String type){ String hql = " FROM UrlFilter t WHERE t.node=? and t.status=? and t.type=?"; return this.find(hql, note, stauts, type); }