cn.dayuanzi.dao.BaseDao.java Source code

Java tutorial

Introduction

Here is the source code for cn.dayuanzi.dao.BaseDao.java

Source

package cn.dayuanzi.dao;

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $
 */

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import cn.dayuanzi.util.ReflectionUtils;

/**
 * ?HibernateAPIDAO.
 * 
 * ?Service, ?DAO?, ?.
 * ?Spring2.5Petlinc?, ?HibernateTemplate, HibernateAPI.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 */
@SuppressWarnings("unchecked")
@Repository
public class BaseDao<PK extends Serializable, T> {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected SessionFactory sessionFactory;

    protected Class<T> entityClass;

    /**
     * Dao?.
     * ??Class.
     */
    public BaseDao() {
        this.entityClass = (Class<T>) ReflectionUtils.getSuperClassGenricType(getClass());
    }

    /**
     * ?Dao, ServiceSimpleHibernateDao.
     * Class.
     */
    public BaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        this.sessionFactory = sessionFactory;
        this.entityClass = entityClass;
    }

    /**
     * ?sessionFactory.
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * @AutowiredSessionFactory, SesionFactory??.
     */
    @Autowired
    public void setSessionFactory(final SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * ??Session.
     */
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * ?.
     */
    public void save(final T entity) {
        Assert.notNull(entity, "entity?");
        //      getSession().saveOrUpdate(entity);
        getSession().save(entity);
        logger.debug("save entity: {}", entity);
    }

    public void saveOrUpdate(final T entity) {
        Assert.notNull(entity, "entity?");
        getSession().saveOrUpdate(entity);
        logger.debug("save entity: {}", entity);
    }

    /**
     * .
     * 
     * @param entity session?idtransient.
     */
    public void delete(final T entity) {
        Assert.notNull(entity, "entity?");
        getSession().delete(entity);
        logger.debug("delete entity: {}", entity);
    }

    /**
     * id.
     */
    public T delete(final PK id) {
        Assert.notNull(id, "id?");
        T entity = get(id);
        if (entity == null) {
            return null;
        }
        delete(entity);
        logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id);
        return entity;
    }

    public T get(final PK id) {
        Assert.notNull(id, "id?");
        return (T) getSession().get(entityClass, id);
    }

    public T load(final PK id) {
        Assert.notNull(id, "id?");
        return (T) getSession().load(entityClass, id);
    }

    /**
     * id?.
     */
    public List<T> get(final Collection<PK> ids) {
        return find(Restrictions.in(getIdName(), ids));
    }

    /**
     *   ?.
     */
    public List<T> getAll() {
        return find();
    }

    /**
     *   ?, ??.
     */
    public List<T> getAll(String orderByProperty, boolean isAsc, Criterion... criterions) {
        Criteria c = createCriteria(criterions);
        if (isAsc) {
            c.addOrder(Order.asc(orderByProperty));
        } else {
            c.addOrder(Order.desc(orderByProperty));
        }
        return c.list();
    }

    /**
     * , ??.
     */
    public List<T> findBy(final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName?");
        Criterion criterion = Restrictions.eq(propertyName, value);
        return find(criterion);
    }

    /**
     * , ??.
     */
    public T findUniqueBy(final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName?");
        Criterion criterion = Restrictions.eq(propertyName, value);
        return (T) createCriteria(criterion).uniqueResult();
    }

    /**
     * HQL.
     * 
     * @param values ????,?.
     */
    public <X> List<X> find(final String hql, final Object... values) {
        return createQuery(hql, values).list();
    }

    /**
     * HQL.
     * 
     * @param values ???,??.
     */
    public <X> List<X> find(final String hql, final Map<String, ?> values) {
        return createQuery(hql, values).list();
    }

    /**
     * HQL.
     * 
     * @param values ????,?.
     */
    public <X> X findUnique(final String hql, final Object... values) {
        return (X) createQuery(hql, values).uniqueResult();
    }

    /**
     * HQL.
     * 
     * @param values ???,??.
     */
    public <X> X findUnique(final String hql, final Map<String, ?> values) {
        return (X) createQuery(hql, values).uniqueResult();
    }

    /**
     * HQL?/?.
     * 
     * @param values ????,?.
     * @return .
     */
    public int batchExecute(final String hql, final Object... values) {
        return createQuery(hql, values).executeUpdate();
    }

    /**
     * HQL?/?.
     * 
     * @param hql ?
     * @param values ???,??.
     * @return .
     */
    public int batchExecute(final String hql, final Map<String, ?> values) {
        return createQuery(hql, values).executeUpdate();
    }

    /**
     * ?HQL?Query.
     * find()???.
     * 
     * @param values ????,?.
     */
    public Query createQuery(final String queryString, final Object... values) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createQuery(queryString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return query;
    }

    /**
     * ?sql?Query.
     * find()???.
     * 
     * @param values ????,?.
     */
    public Query createSqlQuery(final String queryString, final Map<String, ?> values) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createSQLQuery(queryString);
        if (values != null) {
            query.setProperties(values);
        }
        return query;
    }

    /**
     * ?HQL?Query.
     * find()???.
     * 
     * @param values ???,??.
     */
    public Query createQuery(final String queryString, final Map<String, ?> values) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createQuery(queryString);
        if (values != null) {
            query.setProperties(values);
        }
        return query;
    }

    /**
     * Criteria.
     * 
     * @param criterions ???Criterion.
     */
    public List<T> find(final Criterion... criterions) {
        return createCriteria(criterions).list();
    }

    /**
     * Criteria.
     * 
     * @param criterions ???Criterion.
     */
    public T findUnique(final Criterion... criterions) {
        return (T) createCriteria(criterions).uniqueResult();
    }

    /**
     * ?Criterion?Criteria.
     * find()???.
     * 
     * @param criterions ???Criterion.
     */
    public Criteria createCriteria(final Criterion... criterions) {
        Criteria criteria = getSession().createCriteria(entityClass);
        for (Criterion c : criterions) {
            criteria.add(c);
        }
        return criteria;
    }

    /**
     * ?.
     * load()Proxy, View???.
     * entity, ??entity,????.
     * ??,:
     * Hibernate.initialize(user.getRoles())?User??.
     * Hibernate.initialize(user.getDescription())?UserDescription.
     */
    public void initProxyObject(Object proxy) {
        Hibernate.initialize(proxy);
    }

    /**
     * Flush?Session.
     */
    public void flush() {
        getSession().flush();
    }

    /**
     * Querydistinct transformer.
     * ?HQL??, ?distinct?.
     */
    public Query distinct(Query query) {
        query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return query;
    }

    /**
     * Criteriadistinct transformer.
     * ?HQL??, ?distinct?.
     */
    public Criteria distinct(Criteria criteria) {
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria;
    }

    /**
     * ???.
     */
    public String getIdName() {
        ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
        return meta.getIdentifierPropertyName();
    }

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

    /**
     * 
     * 
     * @param hql
     * @param current_page
     * @param max_num
     * @param map
     * @return
     */
    public List<T> findForPage(String hql, int current_page, int max_num, Map<String, Object> map) {
        List<T> result = null;
        if (current_page <= 0) {
            current_page = 1;
        }
        if (max_num > 20) {
            max_num = 20;
        } else if (max_num <= 0) {
            max_num = 1;
        }
        try {
            if (!hql.contains("where")) {
                hql = hql.concat(" where 1=1 ");
            }
            if (map != null) {
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    hql = hql.concat(" and " + key + " =:" + key);
                }
            }
            Query query = this.getSession().createQuery(hql);
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                query.setParameter(key, map.get(key));
            }
            query.setFirstResult(((current_page - 1)) * max_num);
            query.setMaxResults(max_num);
            result = query.list();
        } catch (RuntimeException re) {
            throw re;
        }
        return result;
    }

    /**
     * ?
     * 
     * @param current_page >=1
     * @param max_num >=1 <=1000
     * @param map
     * @param orderByProperty
     * @param isAsc
     * @return
     */
    public List<T> findForPage(int current_page, int max_num, Map<String, Object> map, String orderByProperty,
            boolean isAsc) {
        List<T> result = null;
        if (current_page <= 0) {
            current_page = 1;
        }
        if (max_num > 20) {
            max_num = 20;
        } else if (max_num <= 0) {
            max_num = 1;
        }
        Criteria c = createCriteria();
        if (MapUtils.isNotEmpty(map)) {
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                c.add(Restrictions.eq(key, map.get(key)));
            }
        }
        c.setFirstResult(((current_page - 1)) * max_num);
        c.setMaxResults(max_num);
        if (StringUtils.isNotBlank(orderByProperty)) {
            if (isAsc) {
                c.addOrder(Order.asc(orderByProperty));
            } else {
                c.addOrder(Order.desc(orderByProperty));
            }
        }
        result = c.list();
        return result;
    }

    public List<T> findForPage(int current_page, int max_num, String orderByProperty, boolean isAsc,
            final Criterion... criterions) {
        List<T> result = null;
        if (current_page <= 0) {
            current_page = 1;
        }
        if (max_num > 20) {
            max_num = 20;
        } else if (max_num <= 0) {
            max_num = 1;
        }
        Criteria c = createCriteria(criterions);
        c.setFirstResult(((current_page - 1)) * max_num);
        c.setMaxResults(max_num);
        if (StringUtils.isNotBlank(orderByProperty)) {
            if (isAsc) {
                c.addOrder(Order.asc(orderByProperty));
            } else {
                c.addOrder(Order.desc(orderByProperty));
            }
        }
        result = c.list();
        return result;
    }

    /**
     * ????
     * 
     * @param hql
     * @param map
     * @return
     */
    public int count(String hql, Map<String, Object> map) {
        int result = 0;
        try {
            if (!hql.contains("where")) {
                hql = hql.concat(" where 1=1 ");
            }
            if (map != null) {
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    hql = hql.concat(" and " + key + " =:" + key);
                }
            }
            Query query = this.getSession().createQuery(hql);
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                query.setParameter(key, map.get(key));
            }
            result = query.list().size();
        } catch (RuntimeException re) {
            throw re;
        }
        return result;
    }

    /**
     * ?
     * 
     * @param propertyName
     * @param value
     * @return
     */
    public long count(final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName?");
        return count(Restrictions.eq(propertyName, value));
    }

    /**
     * ??
     * @param criterions
     * @return
     */
    public long count(final Criterion... criterions) {
        Criteria criteria = createCriteria(criterions);
        criteria.setProjection(Projections.rowCount());
        return (long) criteria.uniqueResult();
    }
}