Java tutorial
/** * Copyright (c) 2005-2011 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: HibernateDao.java 1547 2011-05-05 14:43:07Z calvinxiu $ */ package com.age.core.orm.hibernate; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.impl.CriteriaImpl; import org.hibernate.transform.AliasToBeanResultTransformer; import org.hibernate.transform.ResultTransformer; import com.age.core.orm.Page; import com.age.core.orm.PageRequest; import com.age.core.orm.PropertyFilter; import com.age.core.orm.PropertyFilter.MatchType; import com.age.core.utils.AssertUtils; import com.age.core.utils.ReflectionUtils; /** * ?SpringSideHibernat DAO. * * ,?. * * @param <T> DAO? * @param <ID> * * @author calvin */ public class HibernateDao<T, ID extends Serializable> extends SimpleHibernateDao<T, ID> { public static final String DEFAULT_ALIAS = "x"; /** * ??Class. * eg. * public class UserDao extends HibernateDao<User, Long>{ * } */ public HibernateDao() { super(); } public HibernateDao(Class<T> entityClass) { super(entityClass); } //-- --// /** * ?. */ public Page<T> getAll(final PageRequest pageRequest) { return findPage(pageRequest); } /** * HQL. * * @param pageRequest ?. * @param hql hql?. * @param values ????,?. * * @return , ??. */ public Page<T> findPage(final PageRequest pageRequest, String hql, final Object... values) { AssertUtils.notNull(pageRequest, "pageRequest?"); Page<T> page = new Page<T>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countHqlResult(hql, values); page.setTotalItems(totalCount); } Query q = createQuery(hql, values); setPageParameterToQuery(q, pageRequest); List result = q.list(); page.setResult(result); return page; } /** * HQL. * * @param page ?. * @param hql hql?. * @param values ???,??. * * @return , ??. */ public Page<T> findPage(final PageRequest pageRequest, String hql, final Map<String, ?> values) { AssertUtils.notNull(pageRequest, "page?"); Page<T> page = new Page<T>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countHqlResult(hql, values); page.setTotalItems(totalCount); } Query q = createQuery(hql, values); setPageParameterToQuery(q, pageRequest); List result = q.list(); page.setResult(result); return page; } public <X> Page<X> findPage(final PageRequest pageRequest, String hql, final Map<String, ?> values, Class<X> clasz) { AssertUtils.notNull(pageRequest, "pageRequest?"); Page<X> page = new Page<X>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countHqlResult(hql, values); page.setTotalItems(totalCount); } Query q = createQuery(hql, values); q.setResultTransformer(new AliasToBeanResultTransformer(clasz)); setPageParameterToQuery(q, pageRequest); List result = q.list(); page.setResult(result); return page; } /** * HQL. * * @param page ?. * @param hql hql?. * @param values ???,??. * * @return , ??. */ public <X> Page<X> findPageSQL(final PageRequest pageRequest, String sql, final Map<String, ?> values, Class<X> clasz) { AssertUtils.notNull(pageRequest, "page?"); Page<X> page = new Page<X>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countSqlResult(sql, values); page.setTotalItems(totalCount); } Query q = createSQLQuery(sql, values); q.setResultTransformer(new AliasToBeanResultTransformer(clasz)); setPageParameterToQuery(q, pageRequest); List result = q.list(); page.setResult(result); return page; } /** * Criteria. * * @param page ?. * @param criterions ???Criterion. * * @return .??. */ public Page<T> findPage(final PageRequest pageRequest, final Criterion... criterions) { AssertUtils.notNull(pageRequest, "page?"); Page<T> page = new Page<T>(pageRequest); Criteria c = createCriteria(criterions); if (pageRequest.isCountTotal()) { long totalCount = countCriteriaResult(c); page.setTotalItems(totalCount); } setPageRequestToCriteria(c, pageRequest); List result = c.list(); page.setResult(result); return page; } public Page<T> findPage(final PageRequest pageRequest, final Criteria criteria) { AssertUtils.notNull(pageRequest, "page?"); Page<T> page = new Page<T>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countCriteriaResult(criteria); page.setTotalItems(totalCount); } setPageRequestToCriteria(criteria, pageRequest); List result = criteria.list(); page.setResult(result); return page; } /** * ?Query,. */ protected Query setPageParameterToQuery(final Query q, final PageRequest pageRequest) { q.setFirstResult(pageRequest.getOffset()); q.setMaxResults(pageRequest.getPageSize()); return q; } /** * ?Criteria,. */ protected Criteria setPageRequestToCriteria(final Criteria c, final PageRequest pageRequest) { AssertUtils.isTrue(pageRequest.getPageSize() > 0, "Page Size must larger than zero"); c.setFirstResult(pageRequest.getOffset()); c.setMaxResults(pageRequest.getPageSize()); return c; } /** * countHql. * * ???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); } } /** * countHql. * * ???hql?,??hql?count?. */ protected long countHqlResult(final String hql, final Map<String, ?> values) { String countHql = prepareCountHql(hql); countHql = StringUtils.replace(countHql, " fetch ", " "); 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 countSqlResult(final String sql, final Map<String, ?> values) { String countHql = prepareCountHql(sql); countHql = StringUtils.replace(countHql, " fetch ", " "); try { Object count = findUniqueSQL(countHql, values); return Long.parseLong(count + ""); } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } private String prepareCountHql(String orgHql) { String countHql = "select count(*) " + removeSelect(removeOrders(orgHql)); return countHql; } private static String removeSelect(String hql) { int beginPos = hql.toLowerCase().indexOf("from"); return hql.substring(beginPos); } private static String removeOrders(String hql) { Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(hql); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, ""); } m.appendTail(sb); return sb.toString(); } /** * countCriteria. */ 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) c.setProjection(Projections.rowCount()).uniqueResult(); long totalCount = (totalCountObject != null) ? totalCountObject : 0; // ?Projection,ResultTransformerOrderBy?? 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 ??,????PropertyFilterMatcheType 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 PageRequest pageRequest, final List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return findPage(pageRequest, criterions); } /** * ??Criterion,. */ protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) { AssertUtils.hasText(propertyName, "propertyName?"); Criterion criterion = null; //?MatchTypecriterion 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()]); } /*public Page<T> findPage(final PageRequest pageRequest, final DetachedCriteria detachedCriteria) { AssertUtils.notNull(pageRequest, "pageRequest?"); Criteria c = detachedCriteria.getExecutableCriteria(this.getSession()); Page<T> page = new Page<T>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countCriteriaResult(c); page.setTotalItems(totalCount); } setPageRequestToCriteria(c, pageRequest); List result = c.list(); page.setResult(result); return page; }*/ }