net.umpay.mailbill.hql.orm.hibernate.HibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for net.umpay.mailbill.hql.orm.hibernate.HibernateDao.java

Source

/**
 * 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 net.umpay.mailbill.hql.orm.hibernate;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.umpay.mailbill.hql.orm.Page;
import net.umpay.mailbill.hql.orm.PropertyFilter;
import net.umpay.mailbill.hql.orm.PropertyFilter.MatchType;
import net.umpay.mailbill.util.reflect.ReflectionUtils;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
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;

/**
 * ?SpringSideHibernat DAO.
 * 
 * ,?.
 * ?Service,?DAO?,?.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 * @author calvin
 */
public abstract class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {
    /**
     * Dao?.
     * ??Class.
     * eg.
     * public class UserDao extends HibernateDao<User, Long>{
     * }
     */
    public HibernateDao() {
        super();
    }

    /**
     * ?Dao, ServiceHibernateDao.
     * 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 , ??.
     */
    @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);
            if (page.getPageNo() > page.getTotalPages()) {
                page.setPageNo(Integer.valueOf(String.valueOf(page.getTotalPages())));
            }
        }

        setPageParameter(q, page);
        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * HQL.
     * 
     * @param page ?.
     * @param hql hql?.
     * @param values ???,??.
     * 
     * @return , ??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    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);
            if (page.getPageNo() > page.getTotalPages()) {
                page.setPageNo(Integer.valueOf(String.valueOf(page.getTotalPages())));
            }
        }

        setPageParameter(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * SQL.
     * 
     * @param page ?.??orderBy?.
     * @param sql sql?.
     * @param values ????,?.
     * 
     * @return , ??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findSQLPage(final Page<T> page, final String sql, final Object... values) {
        Assert.notNull(page, "page?");

        SQLQuery q = createSQLQuery(sql, values);

        if (page.isAutoCount()) {
            long totalCount = countSqlResult(sql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameter(q, page);

        String className = entityClass.getSimpleName();
        if (!className.equals("Object") && !className.equals("Object[]")) {
            q.addEntity(entityClass);
        }
        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * SQL.
     * 
     * @param page ?.
     * @param sql hql?.
     * @param values ???,??.
     * 
     * @return , ??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findSQLPage(final Page<T> page, final String sql, final Map<String, ?> values) {
        Assert.notNull(page, "page?");

        SQLQuery q = createSQLQuery(sql, values);

        if (page.isAutoCount()) {
            long totalCount = countSqlResult(sql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameter(q, page);

        String className = entityClass.getSimpleName();
        if (!className.equals("Object") && !className.equals("Object[]")) {
            q.addEntity(entityClass);
        }
        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * Criteria.
     * 
     * @param page ?.
     * @param criterions ???Criterion.
     * 
     * @return .??.
     */
    @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);
            if (page.getPageNo() > page.getTotalPages()) {
                page.setPageNo(Integer.valueOf(String.valueOf(page.getTotalPages())));
            }
        }

        setPageParameter(c, page);
        List result = c.list();
        page.setResult(result);
        return page;
    }

    /**
     * Criteria.
     * 
     * @param page ?.
     * @param criteria
     * 
     * @return .??.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Page<T> findPage(final Page<T> page, final Criteria criteria) {
        Assert.notNull(page, "page?");

        if (page.isAutoCount()) {
            int totalCount = countCriteriaResult(criteria);
            page.setTotalCount(totalCount);
            if (page.getPageNo() > page.getTotalPages()) {
                page.setPageNo(Integer.valueOf(String.valueOf(page.getTotalPages())));
            }
        }

        setPageParameter(criteria, page);
        List result = criteria.list();
        page.setResult(result);
        return page;
    }

    /**
     * ?Query,.
     */
    protected Query setPageParameter(final Query q, final Page<T> page) {
        //hibernatefirstResult??0
        if (page.isPageDown()) {
            q.setFirstResult(page.getFirst() - 1);
            q.setMaxResults(page.getPageSize());
        }
        return q;
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameter(final Criteria c, final Page<T> page) {
        //hibernatefirstResult??0
        if (page.isPageDown()) {
            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 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(*) " + fromHql.replaceAll("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);
        }
    }

    /**
     * countHql.
     * 
     * ???hql?,??hql?count?.
     */
    protected long countHqlResult(final String hql, final Map<String, ?> values) {
        String fromHql = hql;
        //select??order by???count,?.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql.replaceAll("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 Object... values) {

        String countHql = "select count(1) from (" + sql + ") totalcount";

        try {
            BigInteger count = new BigInteger(findUniqueSql(countHql, values).toString());
            return count.longValue();
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    public long countSqlResult(final String sql, final Map<String, ?> values) {

        String countHql = "select count(1) from (" + sql + ") totalcount";

        try {
            BigInteger count = new BigInteger(findUniqueSql(countHql, values).toString());
            return count.longValue();
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    /**
     * countCriteria.
     */
    @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);
        }

        // 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);
        }

        return totalCount;
    }

    /**
     * countCriteria.??
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected int countCriteriaResultByCache(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
        int totalCount = (Integer) c.setProjection(Projections.rowCount()).setCacheable(true).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);
        }

        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);
    }

    /**
     * ?.
     */
    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);
    }

    /**
     * ?Criterion,.
     */
    protected Criterion[] buildPropertyFilterCriterions(final List<PropertyFilter> filters) {
        List<Criterion> criterionList = new ArrayList<Criterion>();
        for (PropertyFilter filter : filters) {
            if (!filter.isMultiProperty()) { //??.
                Criterion criterion = buildPropertyFilterCriterion(filter.getPropertyName(),
                        filter.getPropertyValue(), filter.getMatchType());
                criterionList.add(criterion);
            } else {//??,or?.
                Disjunction disjunction = Restrictions.disjunction();
                for (String param : filter.getPropertyNames()) {
                    Criterion criterion = buildPropertyFilterCriterion(param, filter.getPropertyValue(),
                            filter.getMatchType());
                    disjunction.add(criterion);
                }
                criterionList.add(disjunction);
            }
        }
        return criterionList.toArray(new Criterion[criterionList.size()]);
    }

    /**
     * ??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);
            } else if (MatchType.NE.equals(matchType)) {
                criterion = Restrictions.ne(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);
    }
}