jp.ac.tokushima_u.is.ll.common.orm.hibernate.SimpleHibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for jp.ac.tokushima_u.is.ll.common.orm.hibernate.SimpleHibernateDao.java

Source

/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java 624 2009-11-05 13:31:47Z calvinxiu $
 */
package jp.ac.tokushima_u.is.ll.common.orm.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jp.ac.tokushima_u.is.ll.util.ReflectionUtils;
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.DetachedCriteria;
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.util.Assert;

/**
 * Hibernate DAO
 * 
 * Service????DAO??
 * Spring2.5?Petlinc???,HibernateTemplate??Hibernate?API?????.
 * 
 * @param <T> DAODAO??
 * @param <PK> ?
 * 
 * @author calvin
 */
@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.getSuperClassGenricType(getClass());
    }

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

    /**
     * Annotation@Autowired??SessionFactory????SesionFactory?????Override
     */
    @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 should not be null");
        getSession().saveOrUpdate(entity);
        logger.debug("save entity: {}", entity);
    }

    /**
     * 
     *
     * @param entity ??session?????id????transient.
     */
    public void delete(final T entity) {
        Assert.notNull(entity, "entity should not be null");
        getSession().delete(entity);
        logger.debug("delete entity: {}", entity);
    }

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

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

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

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

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

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

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

    /**
     * HQL??.
     *
     * @param values HQL????.
     */
    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, Object> values) {
        return createQuery(hql, values).list();
    }

    /**
     * HQL???.
     *
     * @param values HQL,??.
     */
    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, Object> values) {
        return (X) createQuery(hql, values).uniqueResult();
    }

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

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

    /**
     * HQL??Query?
     *
     * ???find()??????T???T???????????.
     *
     * @param values HQL,??.
     */
    public Query createQuery(final String queryString, final Object... values) {
        Assert.hasText(queryString, "queryString should not be null");
        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?
     *
     * @param values ??,????.
     */
    public Query createQuery(final String queryString, final Map<String, Object> values) {
        Assert.hasText(queryString, "queryString should not be null");
        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();
    }

    public List<T> find(DetachedCriteria detachedCriteria) {
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        return criteria.list();
    }

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

    /**
     * Criterion?Criteria?.
     *
     * ???find()??????T???T???????????.
     *
     * @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??????,????????????.
     * ???????????:
     * Hibernate.initialize(user.getRoles())User????????.
     * Hibernate.initialize(user.getDescription())User???LazyLoad?Description??.
     */
    public void initEntity(T entity) {
        Hibernate.initialize(entity);
    }

    /**
     * @see #initEntity(Object)
     */
    public void initEntity(List<T> entityList) {
        for (T entity : entityList) {
            Hibernate.initialize(entity);
        }
    }

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

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

    /**
     * Set??????
     * ?HQL/Criteria???Preload??????????????distinct????.
     */
    public <X> List<X> distinct(@SuppressWarnings("rawtypes") List list) {
        Set<X> set = new LinkedHashSet<X>(list);
        return new ArrayList<X>(set);
    }

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