com.xdtech.core.orm.hibernate.SimpleHibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for com.xdtech.core.orm.hibernate.SimpleHibernateDao.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java 1594 2011-05-11 14:22:29Z calvinxiu $
 */
package com.xdtech.core.orm.hibernate;

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

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.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.xdtech.core.orm.utils.AssertUtils;
import com.xdtech.core.orm.utils.ReflectionUtils;

/**
 * HibernateAPIDAO.
 * 
 * Spring2.5Petlinc, HibernateTemplate, HibernateAPI.
 * 
 * @param <T> DAO
 * @param <ID> 
 * 
 * @author calvin
 */
public class SimpleHibernateDao<T, ID extends Serializable> {

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

    protected SessionFactory sessionFactory;

    protected Class<T> entityClass;

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

    public SimpleHibernateDao(Class<T> entityClass) {
        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) {
        AssertUtils.notNull(entity, "entity");
        getSession().saveOrUpdate(entity);
        logger.debug("save entity: {}", entity);
    }

    public void saveAll(final List<T> entities) {
        AssertUtils.notNull(entities, "entity");
        for (T entity : entities) {
            save(entity);
        }
        logger.debug("save entities: {}", entities);
    }

    /**
     * .
     * 
     * @param entity sessionidtransient.
     */
    public void delete(final T entity) {
        AssertUtils.notNull(entity, "entity");
        getSession().delete(entity);
        logger.debug("delete entity: {}", entity);
    }

    public void deleteAll(final List<T> entities) {
        AssertUtils.notNull(entities, "entity");
        for (T entity : entities) {
            delete(entity);
        }
        logger.debug("delete entities: {}", entities);
    }

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

    /**
     * id.
     */
    public T get(final ID id) {
        AssertUtils.notNull(id, "id");
        return (T) getSession().load(entityClass, id);
    }

    /**
     * id.
     */
    public List<T> get(final Collection<ID> 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();
    }

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

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

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

    public <X> List<X> findByClass(Class<?> cls) {
        return createHqlQuery("from " + cls.getSimpleName()).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) createHqlQuery(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 createHqlQuery(hql, values).executeUpdate();
    }

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

    /**
     * HQLQuery.
     * find().
     * 
     * @param values ,.
     */
    public Query createHqlQuery(final String queryString, final Object... values) {
        AssertUtils.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;
    }

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

    /**
     * SQLQuery.
     * find().
     * @param sqlQueryString sql
     * 
     * @param values ,.
     */
    public Query createSQLQuery(final String sqlQueryString, final Object... values) {
        Query query = getSession().createSQLQuery(sqlQueryString);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        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();
    }

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

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

}