com.rosy.bill.dao.hibernate.SimpleHibernateDao.java Source code

Java tutorial

Introduction

Here is the source code for com.rosy.bill.dao.hibernate.SimpleHibernateDao.java

Source

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java,v 1.1 2011/03/28 08:01:25 zwm Exp $
 */
package com.rosy.bill.dao.hibernate;

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

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
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.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

//import com.ruanko.sdb2b.dao.Dao;
import com.rosy.bill.utils.reflection.ReflectionUtils;

/**
 * ?HibernateAPIDAO.
 * 
 * ?Service, ?DAO?, ?.
 * ?Spring2.5Petlinc?, ?HibernateTemplate, HibernateAPI.
 * 
 * @param <T> DAO?
 * @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, 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();
    }

    /**
     * ?.
     */
    public void save(final T entity) {
        Assert.notNull(entity, "entity?");
        try {
            getSession().saveOrUpdate(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        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 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);
        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) {
        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) {
        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();
    }

    /**
     * SQL.
     * 
     * @param values ???,??.
     */
    public <X> X findUniqueBySql(final String sql, final Object[] values, final Type... types) {
        return (X) createSqlQuery(sql, values, types).uniqueResult();
    }

    /**
     * SQL.
     * 
     * @param values ???,??.
     */
    public <X> X findUniqueBySql(final String sql, final Map<String, ?> values) {
        return (X) createSqlQuery(sql, 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;
    }

    /**
     * ?SQL?Query.
     * find()???.
     * 
     * @param values .
     * @param queryString
     * @param values ??
     * @param types  ??
     * @return
     */
    public Query createSqlQuery(final String queryString, final Object[] values, final Type... types) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createSQLQuery(queryString);
        if (values != null) {

            query.setParameters(values, types);
        }
        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;
    }

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

    /**
     * ?String
     * @param execStr
     * @param params
     * @param outIndex
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getNumByExecuteProc(String execStr, String[] params, int outIndex) {
        java.sql.CallableStatement cstmt = null;
        String rtn = null;
        try {
            cstmt = this.getSession().connection().prepareCall(execStr);
            cstmt.registerOutParameter(outIndex, oracle.jdbc.driver.OracleTypes.LONGVARCHAR);
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    if (i != outIndex) {
                        cstmt.setString(i, params[i].toString());
                    }
                }
            }
            cstmt.executeQuery();
            java.sql.ResultSet rs = (java.sql.ResultSet) cstmt.getObject(outIndex);
            if (rs != null) {
                rtn = rs.getString(0);
            }
        } catch (HibernateException e1) {
            e1.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rtn;
    }

    @SuppressWarnings("deprecation")
    public String callProc(final String proc, final List<Object> paramList, final int outIndex, final int outType) {
        String result = null;
        java.sql.Connection conn = null;
        java.sql.CallableStatement cstmt = null;
        //Session session = this.getSession();
        try {

            conn = this.getSession().connection();
            conn.setAutoCommit(false);
            cstmt = conn.prepareCall(proc);
            for (int i = 0; paramList != null && i < paramList.size(); i++) {
                if (i + 1 == outIndex) {
                    //cstmt.setInt(i + 1,
                    //      (Integer.parseInt(paramList.get(i).toString())));
                    cstmt.setString(i + 1, paramList.get(i).toString());
                } else {
                    cstmt.setInt(i + 1, Integer.valueOf(paramList.get(i).toString()));
                }
            }
            cstmt.registerOutParameter(outIndex, outType);
            cstmt.execute();
            result = cstmt.getString(outIndex);
            conn.commit();
            //session.flush();
            //session.clear();
        } catch (Exception ex) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                logger.error("[" + proc + "]?" + e1.getMessage());
                e1.printStackTrace();
            }
            ex.printStackTrace();
        } finally {
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (Exception ex) {
                }
            }
        }
        return result;
    }

}