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

Java tutorial

Introduction

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

Source

/**
 * 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 $
 */
package com.hyzy.core.orm.hibernate;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Table;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
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.util.Assert;

import com.hyzy.core.utils.ClassUtils;
import com.hyzy.core.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();
    }

    /**
     * @deprecated
     * @see saveEntity(); ?.
     */
    public void save(final T entity) {
        Assert.notNull(entity, "entity?");
        getSession().saveOrUpdate(entity);
    }

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

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

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

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

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

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

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

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

    /**
     * ?
     * 
     * @author : lizhong0815@163.com
     * @param propertyName : ??
     * @param value : 
     * @return : 
     */
    public T get(final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName ?");
        Assert.notNull(value, "value ?");
        String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";
        return (T) getSession().createQuery(hql).setParameter(0, value).uniqueResult();
    }

    /**
     * ?.
     */
    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 findUniqueBySql(final String sql, final List<Object> values) {
        return (X) createSqlQuery(sql, 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?/?.
     * 
     * @author:chengkunxf
     * @param sql
     * @param values ???,??.
     * @return .
     */
    public int batchExecuteSql(final String sql, final Map<String, ?> values) {
        return createSqlQuery(sql, 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;
    }

    public Query createSqlQuery(final String queryString, final List<Object> values) {
        Assert.hasText(queryString, "queryString?");
        Query query = getSession().createSQLQuery(queryString);
        if (values != null) {
            for (int i = 0; i < values.size(); i++) {
                query.setParameter(i, values.get(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()???.
     * 
     * @author:chengkunxf
     * @param queryString
     * @param values ???,??.
     * @return
     */
    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();
    }

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

    protected Criteria createAlias(Criteria criteria, String... aliasBeans) {
        if (aliasBeans != null && aliasBeans.length > 0) {
            for (int i = 0; i < aliasBeans.length; i++) {
                criteria.createAlias(aliasBeans[i], aliasBeans[i], CriteriaSpecification.LEFT_JOIN);
            }
        }
        return criteria;
    }

    public List<T> find(final String[] aliasBeans, final Criterion... criterions) {
        Criteria criteria = createCriteria(criterions);
        criteria = createAlias(criteria, aliasBeans);
        return criteria.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);
    }

    /**
     * sql?  ? ? ?
     * 
     * @author:chengkunxf
     * @param field ??
     * @param value 
     * @param ids ids
     * @return
     */
    public int updateValueByField(String field, Object value, PK... ids) {

        Assert.notNull(entityClass, "entityClass?");

        String tableName = null;
        if (entityClass.isAnnotationPresent(Table.class)) {
            Table table = entityClass.getAnnotation(Table.class);
            tableName = table.name();
        }
        Assert.notNull(tableName, "???");
        int i = 0;
        StringBuffer sql = new StringBuffer("update ");
        sql.append(tableName);
        sql.append(" set ").append(field);
        sql.append(" = ").append(":value");
        sql.append(" where id in( :id )");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("value", value);
        map.put("id", ids);
        i = batchExecuteSql(sql.toString(), map);
        return i;

    }

    /**
     *  ? ?
     * 
     * @author: chengkunxf
     * @param ids ?id
     * @return ??
     */
    public boolean logicDelete(final PK... ids) {
        Assert.notNull(entityClass, "entityClass?");
        Assert.notNull(ids, "?");

        StringBuffer hql = new StringBuffer("update ");
        hql.append(entityClass.getName());

        int i = 0;
        if (ids.length == 0) {
            hql.append(" set status = -100 where id =:id");

            i = this.createQuery(hql.toString(), ids[0]).executeUpdate();
        } else {
            hql.append(" set status = -100 where id in(:id)");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", ids);
            i = batchExecute(hql.toString(), map);
        }

        if (i >= 0) {
            return true;
        }
        return false;
    }

    /**
     * ?? ?/???
     * 
     * @author: lizhong
     * @param ids ?id
     * @return ??
     */
    public void delete(final PK... ids) {
        Assert.notEmpty(ids, "ids ?");
        for (PK id : ids) {
            T entity = get(id);
            getSession().delete(entity);
        }
    }

    /**
     * ?? ?/?sql????
     * 
     * @author: lizhong
     * @param ids ?id
     * @return ??
     */
    public boolean deleteBySql(final PK... ids) {
        Assert.notNull(entityClass, "entityClass?");
        Assert.notNull(ids, "?");

        StringBuffer hql = new StringBuffer("delete ");
        hql.append(entityClass.getName());

        int i = 0;
        if (ids.length == 0) {
            hql.append(" where id =:id");

            i = this.createQuery(hql.toString(), ids[0]).executeUpdate();
        } else {
            hql.append(" where id in(:id)");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", ids);
            i = batchExecute(hql.toString(), map);
        }

        if (i >= 0) {
            return true;
        }
        return false;
    }

    /**
     * ??Criterion??
     * 
     *
     * 
     * @author: zhaozongzhan
     * 
     * @create: 201615 ?10:28:26
     * 
     *
     * 
     * @param showFieldNames//??
     * @param criterions ?
     * @return showFieldNamesNULL0?? ??
     *         com.hyzy.core.orm.hibernate.
     *         HibernateDao??getAppointedFieldNamesByEntity?
     */
    public List<T> findShowFields(List<String> showFieldNames, final Criterion... criterions) {
        return setShowFields(showFieldNames, criterions).list();

    }

    /**
     * ??Criterion??
     * 
     *
     * 
     * @author: zhaozongzhan
     * 
     * @create: 2016114 ?5:21:27
     * 
     *
     * @param showFieldNames//??
     * @param criterions ?
     * @return showFieldNamesNULL0?? ??
     *         com.hyzy.core.orm.hibernate.
     *         HibernateDao??getAppointedFieldNamesByEntitys?
     * 
     * @return
     */
    public Object findShowFieldsUniqueResult(List<String> showFieldNames, final Criterion... criterions) {
        Criteria c = null;
        if (showFieldNames != null && showFieldNames.size() > 0)
            c = setShowFields(showFieldNames, criterions);
        else
            c = createCriteria(criterions);
        return c.uniqueResult();

    }

    /**
     * 
     * 
     * ??
     * 
     * @author: zhaozongzhan
     * 
     * @create: 2016113 ?10:40:57
     * 
     *
     * 
     * @param showFieldNames ?
     * @param criterions
     * @return
     */
    protected Criteria setShowFields(List<String> showFieldNames, final Criterion... criterions) {
        Criteria criteria = createCriteria(criterions);
        if (showFieldNames != null && showFieldNames.size() > 0) {
            ProjectionList proList = Projections.projectionList();// ?
            for (String fieldName : showFieldNames) {

                proList.add(Projections.property(fieldName));
            }
            criteria.setProjection(proList);
        }

        return criteria;
    }

    /**
     * 
        
     *
        
     * @author: zhaozongzhan
        
     * @create: 2016128 ?5:28:07
        
     *
        
     * @param valuesMap 
     * 
     * 
     * Map<String,Object> clearModelMap=new  HashMap<String,Object>();
       clearModelMap.put("id", 27016L);//?ID?
       clearModelMap.put("supplierName","?111111111111111111ZZZqqxxx");
       bs.updateClearModel(clearModelMap);
     * @return
     */
    public boolean updateAppointedFieldNamesByEntity(Map<String, Object> updateValuesMap) {
        Assert.notNull(updateValuesMap, "valuesMap?");
        StringBuffer hqlbuf = new StringBuffer();
        hqlbuf.append(" update ");
        hqlbuf.append(entityClass.getSimpleName());
        hqlbuf.append("  set ");
        List<Object> parVales = new ArrayList<Object>();

        for (Map.Entry<String, Object> entry : updateValuesMap.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldValue = entry.getValue();
            if ("id".equals(fieldName))
                continue;
            hqlbuf.append(fieldName + " =?,");
            parVales.add(fieldValue);

        }
        parVales.add(updateValuesMap.get("id"));
        Object[] pars = parVales.toArray();

        String hql = hqlbuf.toString();
        hql = hql.substring(0, hql.lastIndexOf(",")) + " where id=?";
        logger.info(" hqlbuf:" + hql);
        int result = -1;
        if (parVales.size() > 1 && updateValuesMap.get("id") != null)
            result = this.createQuery(hql, pars).executeUpdate();
        if (result != 1)
            return false;
        else
            return true;
    }

    /**
     * ?? WEB SESSION
        
        HQL?/?.
     * 
     * @author:chengkunxf
     * @param sql
     * @param values ???,??.
     * @return .
        
     * @author: zhaozongzhan
        
     * @create: 2016316 ?11:17:00
        
     *
        
     * @param sql
     * @param values
     * @return
     */
    public int batchExecuteSqlBeginTransaction(final String sql, final Map<String, ?> values) {
        return createSqlQueryBeginTransaction(sql, values).executeUpdate();
    }

    /**
     * ?? WEB SESSION
        
     *?SQL?Query. find()???.
     * 
     * @author:chengkunxf
     * @param queryString
     * @param values ???,??.
     * @return
        
     * @author: zhaozongzhan
        
     * @create: 2016316 ?11:17:42
        
     *
        
     * @param queryString
     * @param values
     * @return
     */
    public Query createSqlQueryBeginTransaction(final String queryString, final Map<String, ?> values) {
        Assert.hasText(queryString, "queryString?");
        Session s = HibernateUtil.currentSession();
        HibernateUtil.beginTransaction();
        Query query = s.createSQLQuery(queryString);
        if (values != null) {
            query.setProperties(values);
        }
        return query;
    }

    /**
     * ?? WEB SESSION
     * sql?  ? ? ?
     * 
     * @author:chengkunxf
     * @param field ??
     * @param value 
     * @param ids ids
     * @return
        
     * @author: zhaozongzhan
        
     * @create: 2016316 ?11:14:51
        
     *
        
     * @param field
     * @param value
     * @param ids
     * @return
     */
    public int updateValueByFieldBeginTransaction(String field, Object value, Object ids) {

        Assert.notNull(entityClass, "entityClass?");

        String tableName = null;
        if (entityClass.isAnnotationPresent(Table.class)) {
            Table table = entityClass.getAnnotation(Table.class);
            tableName = table.name();
        }
        Assert.notNull(tableName, "???");
        int i = 0;
        StringBuffer sql = new StringBuffer("update ");
        sql.append(tableName);
        sql.append(" set ").append(field);
        sql.append(" = ").append(":value");
        sql.append(" where id in( :id )");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("value", value);
        map.put("id", ids);
        i = batchExecuteSqlBeginTransaction(sql.toString(), map);
        return i;

    }

}