com.project.framework.dao.BaseDao.java Source code

Java tutorial

Introduction

Here is the source code for com.project.framework.dao.BaseDao.java

Source

/**
 * Copyright 2008 - 2010 Simcore.org.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.project.framework.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.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.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.CriteriaImpl.OrderEntry;
import org.hibernate.transform.ResultTransformer;
import org.springframework.util.Assert;
import com.project.framework.controller.Page;
import com.project.framework.util.ReflectionUtils;

/**
 * Hibernat DAO.
 * 
 * ,?.
 * ?Service,?DAO?,?.
 * 
 * @param <T> DAO?
 * @param <ID> 
 * <p>
 * @author ray
 */
@SuppressWarnings("unchecked")
public class BaseDao<T, ID extends Serializable> extends GenericDao<T, ID> {
    /**
     * Dao?.
     * ??Class.
     * eg.
     * public class UserDao extends HibernateDao<User, Long>{
     * }
     */
    public BaseDao() {
        super();
    }

    /**
     * ?Dao, ServiceHibernateDao.
     * Class.
     * eg.
     * HibernateDao<User, Long> userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
     */
    public BaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        super(sessionFactory, entityClass);
    }

    /**
     * HQL.
     * 
     * @param page .??orderBy?.
     * @param queryString ?.
     * @param values ????,?.
     * 
     * @return Page , ??.
     */
    public Page<T> findPage(final Page<T> page, final String queryString, final Object... values) {
        Assert.notNull(page, "page can not null");

        Query q = createQuery(queryString, values);

        if (page.isAutoCount()) {
            long total = countResult(queryString, values);
            page.setTotal(total);
        }

        setPageParameter(q, page);
        List<T> result = q.list();
        page.setRows(result);
        return page;
    }

    /**
     * HQL.
     * 
     * @param page .
     * @param queryString ?.
     * @param values ???,??.
     * 
     * @return , ??.
     */
    public Page<T> findPage(final Page<T> page, final String queryString, final Map<String, ?> values) {
        Assert.notNull(page, "page can not null");

        Query q = createQuery(queryString, values);

        if (page.isAutoCount()) {
            long total = countResult(queryString, values);
            page.setTotal(total);
        }

        setPageParameter(q, page);

        List<T> result = q.list();
        page.setRows(result);
        return page;
    }

    /**
     * Criteria.
     * 
     * @param page .
     * @param criterions ???Criterion.
     * 
     * @return .??.
     */
    public Page<T> findPage(final Page<T> page, final Criterion... criterions) {

        Assert.notNull(page, "page can not null");

        Criteria c = createCriteria(criterions);

        if (page.isAutoCount()) {
            int total = countResult(c);
            page.setTotal(total);
        }

        setPageParameter(c, page);
        List<T> result = c.list();
        page.setRows(result);
        return page;
    }

    public Page<T> findPage(final Page<T> page, final Criterion[] criterions, final Order... orders) {
        Assert.notNull(page, "page can not null");

        Criteria c = createCriteria(criterions);

        if (page.isAutoCount()) {
            int total = countResult(c);
            page.setTotal(total);
        }

        if (orders != null) {
            for (Order order : orders) {
                c = c.addOrder(order);
            }
        }
        setPageParameter(c, page);
        List<T> result = c.list();
        page.setRows(result);
        return page;
    }

    /**
     * ?Query,.
     */
    protected Query setPageParameter(final Query q, final Page<T> page) {
        if (page.getStartIndex() > Integer.MAX_VALUE)
            throw new ClassCastException("Hibernate can not support startIndex Greater than Integer.Max");

        //hibernatefirstResult??0
        q.setFirstResult((int) page.getStartIndex());
        q.setMaxResults(page.getPageSize());

        return q;
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameter(final Criteria c, final Page<T> page) {
        if (page.getStartIndex() > Integer.MAX_VALUE)
            throw new ClassCastException("Hibernate can not support startIndex Greater than Integer.Max");

        //hibernatefirstResult??0
        c.setFirstResult((int) page.getStartIndex());
        c.setMaxResults(page.getPageSize());

        //order by ?
        if (page.isOrder()) {
            Map<String, String> orderMap = page.getOrderMap();
            Iterator<String> iterator = orderMap.keySet().iterator();
            while (iterator.hasNext()) {

                String propertyName = iterator.next();
                if (orderMap.get(propertyName).equals(Page.ORDER_ASC)) {
                    c.addOrder(Order.asc(propertyName));
                } else {
                    c.addOrder(Order.desc(propertyName));
                }
            }
        }
        return c;
    }

    /**
     * count.
     * 
     * ????,???count?.
     */
    public long countResult(final String queryString, final Object... values) {
        String fromHql = queryString;
        //select??order by???count,?.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql;

        try {
            Long count = executeUniqueQuery(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("queryString can't be auto count, queryString is:" + countHql, e);
        }
    }

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

        String countHql = "select count(*) " + fromHql;

        try {
            Long count = executeUniqueQuery(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("queryString can't be auto count, queryString is:" + countHql, e);
        }
    }

    /**
     * countCriteria.
     */
    public int countResult(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<OrderEntry>) ReflectionUtils.getFieldValue(impl, "orderEntries");
            ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList<Object>());
        } catch (Exception e) {
            logger.error("??:{}", e.getMessage());
        }

        // Count
        int totalCount = Integer.parseInt(c.setProjection(Projections.rowCount()).uniqueResult().toString());

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

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