com.lushapp.common.orm.hibernate.SimpleHibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for com.lushapp.common.orm.hibernate.SimpleHibernateDao.java

Source

/**
 *  Copyright (c) 2014 http://www.lushapp.wang
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.lushapp.common.orm.hibernate;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
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.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.util.Assert;

import com.lushapp.common.exception.DaoException;
import com.lushapp.common.orm.Page;
import com.lushapp.common.orm.annotation.Delete;
import com.lushapp.common.utils.ConvertUtils;
import com.lushapp.common.utils.StringUtils;
import com.lushapp.common.utils.reflection.ReflectionUtils;

/**
 * ?HibernateAPIDAO.
 * 
 * ?Service, ?DAO?, ?.
 * ?Spring2.5Petlinc?, ?HibernateTemplate, HibernateAPI.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 * @author honey.zhao@aliyun.com  
 */
@SuppressWarnings("unchecked")
public class SimpleHibernateDao<T, PK extends Serializable> {

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

    protected SessionFactory sessionFactory;

    protected Class<T> entityClass;

    /**
     * Dao?.
     * ??Class.
     * eg.
     * public class UserDao extends SimpleHibernateDao<User, Long>
     */
    public SimpleHibernateDao() {
        this.entityClass = ReflectionUtils.getClassGenricType(getClass());
    }

    /**
     * ?Dao, ServiceSimpleHibernateDao.
     * Class.
     * eg.
     * SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User, Long>(sessionFactory, User.class);
     */
    public SimpleHibernateDao(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();
    }

    /**
     * ??Connection.
     */
    public Connection getConnection() {
        try {
            return SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

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

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

    /**
     * ?.
     * <br>? saveOrUpdate
     * <br>:??session clear()
     */
    public void saveEntity(final T entity) {
        Assert.notNull(entity, "entity?");
        clear();//
        getSession().saveOrUpdate(entity);
        logger.debug("saveOrUpdate entity: {}", entity);
    }

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

    /**
     * ??.
     */
    public void saveOrUpdate(final Collection<T> entitys) {
        Assert.notNull(entitys, "entitys?");
        for (T entity : entitys) {
            this.saveOrUpdate(entity);
        }
    }

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

    /**
     * .
     * <br>?lockOptions?null
     * @param entity ?
     * @param lockOptions Hibernate LockOptions 
     */
    public void refresh(T entity, LockOptions lockOptions) {
        if (lockOptions == null) {
            refresh(entity);
        } else {
            getSession().refresh(entity, lockOptions);
        }
    }

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

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

    /**
     * session????
     * 
     * @param entityName ???
     * @param entity ?
     */
    public void merge(String entityName, T entity) {
        getSession().merge(entityName, entity);
    }

    /**
     * .
     * <br> ?StatusDelete,?.
     * @param entity session?idtransient.
     */
    public void delete(final T entity) {
        Assert.notNull(entity, "entity?");
        Delete delete = ReflectionUtils.getAnnotation(entityClass, Delete.class);
        if (delete != null) {
            Object value = ConvertUtils.convertToObject(delete.value(), delete.type().getValue());
            ReflectionUtils.invokeSetter(entity, delete.propertyName(), value);
            update(entity);
        } else {
            getSession().delete(entity);
        }
        logger.debug("delete entity: {}", entity);
    }

    /**
     * .
     * 
     * @param entitys
     */
    public void deleteAll(Collection<T> entitys) {
        for (Object entity : entitys) {
            getSession().delete(entity);
            getSession().flush();
        }
    }

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

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

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

    /**
     * id?(?,??).
     * @param id
     * @param lockOptions
     * @return
     */
    public T load(Serializable id, LockOptions lockOptions) {
        Assert.notNull(id);
        T entity = null;
        if (lockOptions != null) {
            entity = (T) getSession().load(entityClass, id, lockOptions);
        } else {
            entity = (T) getSession().load(entityClass, id);
        }
        return entity;
    }

    /**
     * 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) {
        Criteria c = createCriteria();
        if (isAsc) {
            c.addOrder(Order.asc(orderByProperty));
        } else {
            c.addOrder(Order.desc(orderByProperty));
        }
        return c.list();
    }

    /**
     * ?, ??.
     * 
     * @param orderBy
     *            ? ?','.
     * @param order
     *            ??"asc"?"desc" ","
     */
    public List<T> getAll(String orderBy, String order) {
        Criteria c = createCriteria();
        //?
        setPageParameterToCriteria(c, orderBy, order);
        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 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;
    }

    /**
     * ?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 orderBy ?','.
     * @param orderBy ? ?','.
     * @param order ??"asc"?"desc" ","
     * @return
     */
    public List<T> find(final String orderBy, final String order, final Criterion... criterions) {
        Criteria c = createCriteria(criterions);
        //?
        setPageParameterToCriteria(c, orderBy, order);
        return c.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();
    }

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

    /**
     * FlushMode.
     */
    public void setFlushMode(FlushMode mode) {
        getSession().setFlushMode(mode);
    }

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

    /**
     * ???
     * 
     * @return String
     */
    public String getEntityName() {
        ClassMetadata meta = sessionFactory.getClassMetadata(entityClass);
        return meta.getEntityName();
    }

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

    //SQL
    /**
     * ?SQL?SQLQuery.
     * 
     * @param values ????,?.
     */
    public SQLQuery createSQLQuery(final String sql, final Object... values) {
        Assert.hasText(sql, "sql?");
        SQLQuery sqlQuery = getSession().createSQLQuery(sql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                sqlQuery.setParameter(i, values[i]);
            }
        }
        return sqlQuery;
    }

    /**
     * ?SQL?SQLQuery.
     * 
     * @param sql
     * @param values ???,??.
     * @return
     */
    public SQLQuery createSQLQuery(final String sql, final Map<String, ?> values) {
        Assert.hasText(sql, "sql?");
        SQLQuery sqlQuery = getSession().createSQLQuery(sql);
        if (values != null) {
            Set<String> set = values.keySet();
            for (String s : set) {
                sqlQuery.setParameter(s, values.get(s));
            }
        }
        return sqlQuery;
    }

    /**
     * sql.
     */
    public void executeJdbcUpdate(String sql) throws DaoException {
        Assert.hasText(sql, "sql?");
        try {
            getConnection().prepareStatement(sql).execute();
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    /**
     * sql.
     */
    public ResultSet executeJdbcQuery(String sql) throws DaoException {
        Assert.hasText(sql, "sql?");
        try {
            return getConnection().prepareStatement(sql).executeQuery();
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    /**
     * entity??session?,true,?false
     * 
     * @param entity 
     * 
     * @return boolean
     */
    public boolean contains(Object entity) {
        return getSession().contains(entity);
    }

    /**
     * ?Criteria,.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final String orderBy, final String order) {
        if (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(order)) {
            String[] orderByArray = StringUtils.split(orderBy, ',');
            String[] orderArray = StringUtils.split(order, ',');

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