com.zc.orm.hibernate.HibernateDao.java Source code

Java tutorial

Introduction

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

Source

/**
 *  Copyright (c) 2012-2014 http://www.eryansky.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.zc.orm.hibernate;

import java.io.Serializable;
import java.util.*;

import com.zc.orm.Page;
import com.zc.util.refelect.Reflector;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;

/**
 * ?SpringSideHibernate DAO.
 * 
 * ,?? ?Service??DAO?,?.
 * 
 * @param <T>
 *            DAO??
 * @param <PK>
 *            
 * 
 */
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? Service?HibernateDao? 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) {

        Query q = createQuery(hql, values);

        if (page.isCountTotal()) {
            long totalItems = countHqlResult(hql, values);
            page.setTotalItems(totalItems);
        }

        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, final Map<String, ?> values) {

        Query q = createQuery(hql, values);

        if (page.isCountTotal()) {
            long totalItems = countHqlResult(hql, values);
            page.setTotalItems(totalItems);
        }

        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) {

        Criteria c = createCriteria(criterions);

        if (page.isCountTotal()) {
            long totalItems = countCriteriaResult(c);
            page.setTotalItems(totalItems);
        }

        setPageParameterToCriteria(c, page);

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

    /**
     * ?Query,.
     */
    public Query setPageParameterToQuery(final Query q, final Page<T> page) {
        q.setFirstResult(page.getFirstResult() - 1);// hibernatefirstResult??0
        q.setMaxResults(page.getPageSize());
        return q;
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {
        c.setFirstResult(page.getFirstResult() - 1);
        c.setMaxResults(page.getPageSize());
        //?
        super.setPageParameterToCriteria(c, page.getOrderBy(), page.getOrderDir());
        return c;
    }

    /**
     * countHql???
     * 
     * ???hql?,??hql?count?.
     */
    public 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);

        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) Reflector.getFieldValue(impl, "orderEntries");
            Reflector.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 {
            Reflector.setFieldValue(impl, "orderEntries", orderEntries);
        } catch (Exception e) {
            logger.error("??:{}", e.getMessage());
        }

        return totalCount;
    }

    /**
     * ???.
     * 
     * @param uniquePropertyNames
     *            POJO???,? "name,loginid,password"
     */
    public boolean isUnique(T entity, String uniquePropertyNames) {
        Criteria criteria = getSession().createCriteria(entityClass).setProjection(Projections.rowCount());
        String[] nameList = uniquePropertyNames.split(",");
        try {
            // 
            for (int i = 0; i < nameList.length; i++) {
                criteria.add(Restrictions.eq(nameList[i], PropertyUtils.getProperty(entity, nameList[i])));
            }

            // ?update,entity.

            String idName = getSessionFactory().getClassMetadata(entity.getClass()).getIdentifierPropertyName();
            if (idName != null) {
                // ?entity
                Serializable id = (Serializable) PropertyUtils.getProperty(entity, idName);

                // id!=null,,?update,
                if (id != null)
                    criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
            }
        } catch (Exception e) {
            Reflector.convertReflectionExceptionToUnchecked(e);
        }
        return ((Number) criteria.uniqueResult()).intValue() == 0;
    }
}