com.jeysan.modules.orm.hibernate.HibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for com.jeysan.modules.orm.hibernate.HibernateDao.java

Source

/**
 * Copyright (c) 2005-2010 jeysan.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: HibernateDao.java 1205 2010-09-09 15:12:17Z shally $
 */
package com.jeysan.modules.orm.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
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.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.ResultTransformer;
import org.springframework.util.Assert;

import com.jeysan.modules.orm.Page;
import com.jeysan.modules.orm.PropertyFilter;
import com.jeysan.modules.orm.PropertyFilter.MatchType;
import com.jeysan.modules.utils.hibernate.HibernateUtils;
import com.jeysan.modules.utils.reflection.ReflectionUtils;

/**
 * ?JeysanHibernat DAO.
 * 
 * ,?.
 * ?Service,?DAO?,?.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 * @author shally
 */
public 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")
    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;
    }

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

        Query q = createSqlQuery(sql, values);

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

        setPageParameterToQuery(q, page);

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

    @SuppressWarnings("unchecked")
    public List findBySql(final String sql, final Object... values) {
        return createSqlQuery(sql, values).list();
    }

    /**
     * HQL.
     * 
     * @param page ?. ???orderBy?.
     * @param hql hql?.
     * @param values ???,??.
     * 
     * @return , ??.
     */
    @SuppressWarnings("unchecked")
    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);
        }

        setPageParameterToQuery(q, page);

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

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

    /**
     * ?Query,.
     */
    protected Query setPageParameterToQuery(final Query q, final Page<T> page) {
        if (page.getPageSize() != -1) {
            //Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

            //hibernatefirstResult??0
            q.setFirstResult(page.getFirst() - 1);
            q.setMaxResults(page.getPageSize());
            return q;
        }
        return q;
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {

        //Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        //hibernatefirstResult??0
        if (page.getPageSize() != -1) {
            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,
                    "???,????");

            return HibernateUtils.checkCriteria4SubOrder(c, orderArray, orderByArray);
        }
        //logger.debug("c:::"+c);
        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);
        }
    }

    protected long countSqlResult(final String sql, final Object... values) {
        String countSql = prepareCountHql(sql);

        try {
            Map count = findUniqueBySql(countSql, values);
            return count.size();
        } catch (Exception e) {
            throw new RuntimeException("Sql can't be auto count, Sql is:" + countSql, e);
        }
    }

    /**
     * countHql.
     * 
     * ???hql?,??hql?count?.
     */
    protected long countHqlResult(final String hql, final Map<String, ?> 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);
        }
    }

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

    /**
     * countCriteria.
     */
    @SuppressWarnings("unchecked")
    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 Page<T> page, final List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return findPage(page, criterions);
    }

    /**
     * ??Criterion,.
     */
    protected Criterion buildCriterion(final String propertyName, final Object propertyValue,
            final MatchType matchType) {
        Assert.hasText(propertyName, "propertyName?");
        Criterion criterion = null;
        //?MatchTypecriterion
        switch (matchType) {
        case EQ:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;
        case NEQ:
            if (propertyValue == null)
                criterion = Restrictions.isNotNull(propertyName);
            else
                criterion = Restrictions.not(Restrictions.eq(propertyName, propertyValue));
            break;
        case NULL:
            criterion = Restrictions.isNull(propertyName);
            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) {
        if (filters == null || filters.size() == 0)
            return new Criterion[] {};
        List<Criterion> criterionList = new ArrayList<Criterion>();
        for (PropertyFilter filter : filters) {
            if (filter == null)
                continue;
            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()]);
    }

    @SuppressWarnings("unchecked")
    protected Criteria getCriteria() {
        return getSession().createCriteria(entityClass);
    }

    @SuppressWarnings("unchecked")
    public Page<T> findPage(final Page<T> page, final Criteria criteria) {
        Assert.notNull(page, "page?");

        if (page.isAutoCount()) {
            long totalCount = countCriteriaResult(criteria);
            page.setTotalCount(totalCount);
        }

        setPageParameterToCriteria(criteria, page);

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