Java tutorial
/** * Copyright (c) 2005-2009 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: HibernateDao.java 763 2009-12-27 18:36:21Z calvinxiu $ */ package com.lakeside.data.sqldb; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.commons.lang.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.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.dialect.Dialect; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.hql.classic.QueryTranslatorImpl; import org.hibernate.impl.CriteriaImpl; import org.hibernate.impl.SessionFactoryImpl; import org.hibernate.transform.ResultTransformer; import org.springframework.util.Assert; import com.lakeside.core.utils.ReflectionUtils; import com.lakeside.data.sqldb.XqlBuilder.MatchType; /** * ?PageBaseDaoBaseDao. * * ,?. * ?Service,?DAO?,?. * * @param <T> DAO? * @param <PK> * * @author calvin */ public class PageBaseDao<T, PK extends Serializable> extends BaseDao<T, PK> { /** * Dao?. * ??Class. * eg. * public class UserDao extends PageBaseDao<User, Long>{ * } */ public PageBaseDao() { super(); } /** * ?Dao, ServiceHibernateDao. * Class. * eg. * PageBaseDao<User, Long> userDao = new PageBaseDao<User, Long>(sessionFactory, User.class); */ public PageBaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) { super(sessionFactory, entityClass); } //-- --// /** * ?. */ public Page<T> getAll(final Page<T> page) { return findPage(page); } /** * HQL. * * @param page ?. * @param hql hql?. * @param values ???,??. * * @return , ??. */ @SuppressWarnings("unchecked") public <X> Page<X> findPage(final Page<X> page, final String hql, final Map<String, ?> values) { Assert.notNull(page, "page?"); if (page.isAutoCount()) { long totalCount = countHqlResult(hql, values); page.setTotalCount(totalCount); } String orderSql = setOrder(hql, page); Query q = createQuery(orderSql, values); setPageParameter(q, page); List<X> result = q.list(); page.setResult(result); return page; } /** * HQL. * * @param page ?. * * @return , ??. */ public <X> Page<X> findPage(final Page<X> page, final XqlBuilder xql) { Assert.notNull(page, "page?"); return findPage(page, xql.getXql(), xql.getParam()); } /** * HQL. * * @param page ?. * @param hql hql?. * @param values ???,??. * * @return , ??. */ @SuppressWarnings("unchecked") public <X> Page<X> findPage(final Page<X> page, final String sql, final Map<String, ?> values, final Class<X> elementType) { Assert.notNull(page, "page?"); if (page.isAutoCount()) { long totalCount = countSqlResult(sql, values); page.setTotalCount(totalCount); } String orderSql = setOrder(sql, page); String pageOrderSql = setPageParameter(orderSql, (Map<String, Object>) values, page); List<X> result = jfind(pageOrderSql, values, elementType); page.setResult(result); return page; } /** * HQL. * * @param page ?. * * @return , ??. */ public <X> Page<X> findPage(final Page<X> page, final XqlBuilder xql, final Class<X> elementType) { Assert.notNull(page, "page?"); return findPage(page, xql.getXql(), xql.getParam(), elementType); } /** * 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()) { int totalCount = countCriteriaResult(c); page.setTotalCount(totalCount); } setPageParameter(c, page); List<T> result = c.list(); page.setResult(result); return page; } protected <X> String setOrder(final String hql, final Page<X> page) { if (!page.isOrderBySetted()) { return hql; } String[] orderByArray = StringUtils.split(page.getOrderBy(), ','); String[] orderArray = StringUtils.split(page.getOrder(), ','); Assert.isTrue(orderByArray.length == orderArray.length, "???,????"); StringBuilder orderSql = new StringBuilder(StringUtils.substringBefore(hql, "order by")); orderSql.append("order by "); for (int i = 0; i < orderByArray.length; i++) { orderSql.append(orderByArray[i]).append(" ").append(orderArray[i]).append(","); } return orderSql.substring(0, orderSql.length() - 1); } protected <X> String setPageParameter(final String sql, final Map<String, Object> values, final Page<X> page) { Dialect dialect = ((SessionFactoryImpl) sessionFactory).getDialect(); String pageSql = dialect.getLimitString(sql, page.getFirst() - 1, page.getPageSize()); boolean hasOffset = page.getFirst() - 1 > 0 || dialect.forceLimitUsage(); if (!hasOffset) { pageSql = pageSql.replace("?", ":pageLimit"); values.put("pageLimit", page.getPageSize()); return pageSql; } if (dialect.bindLimitParametersInReverseOrder()) { pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageLimit"); pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageOffset"); } else { pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageOffset"); pageSql = StringUtils.replaceOnce(pageSql, "?", ":pageLimit"); } values.put("pageOffset", page.getFirst() - 1); values.put("pageLimit", page.getPageSize()); if (dialect.useMaxForLimit()) { values.put("pageLimit", page.getFirst() - 1 + page.getPageSize()); } return pageSql; } /** * ?Query,. */ protected <X> Query setPageParameter(final Query q, final Page<X> page) { //hibernatefirstResult??0 q.setFirstResult(page.getFirst() - 1); q.setMaxResults(page.getPageSize()); return q; } /** * ?Criteria,. */ protected Criteria setPageParameter(final Criteria c, final Page<T> page) { //hibernatefirstResult??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; } /** * countHql. * * ???hql?,??hql?count?. */ protected int countHqlResult(final String hql, final Map<String, ?> values) { String countHql = getCountSql(hql); try { int count = jfindInt(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 int countSqlResult(final String sql, final Map<String, ?> values) { String countSql = "select count(*) from (" + sql + ") totalcount"; try { int count = jfindInt(countSql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countSql, e); } } protected String getCountSql(String originalHql) { QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(originalHql, originalHql, Collections.EMPTY_MAP, (SessionFactoryImplementor) sessionFactory); queryTranslator.compile(Collections.EMPTY_MAP, false); String fromHql = StringUtils.substringBeforeLast(queryTranslator.getSQLString(), "order by"); return "select count(*) from (" + fromHql + ") totalcount"; } /** * countCriteria. */ @SuppressWarnings("unchecked") protected int countCriteriaResult(final Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; // Projection?OrderBy??,??Count? Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List<CriteriaImpl.OrderEntry>) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList<Object>()); } catch (Exception e) { logger.error("??:{}", e.getMessage()); } // Count int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult(); // ?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 = buildPropertyFilterCriterion(propertyName, value, matchType); return find(criterion); } /** * ??Criterion,. */ protected Criterion buildPropertyFilterCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = null; try { //?MatchTypecriterion if (MatchType.EQ.equals(matchType)) { criterion = Restrictions.eq(propertyName, propertyValue); } else if (MatchType.LIKE.equals(matchType)) { criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE); } else if (MatchType.LE.equals(matchType)) { criterion = Restrictions.le(propertyName, propertyValue); } else if (MatchType.LT.equals(matchType)) { criterion = Restrictions.lt(propertyName, propertyValue); } else if (MatchType.GE.equals(matchType)) { criterion = Restrictions.ge(propertyName, propertyValue); } else if (MatchType.GT.equals(matchType)) { criterion = Restrictions.gt(propertyName, propertyValue); } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return criterion; } /** * ??. * * ,(value)?(orgValue)?. */ public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) { if (newValue == null || newValue.equals(oldValue)) { return true; } Object object = findUniqueBy(propertyName, newValue); return (object == null); } }