Package com.wizriver.dao

Source Code of com.wizriver.dao.GenericDaoHibernate

package com.wizriver.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
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.Disjunction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.orm.PropertyFilter.MatchType;

import com.wizriver.entity.VgEntity;
import com.wizriver.reflection.ReflectionUtils;
import com.wizriver.utils.WPage;

/**
* This class serves as the Base class for all other DAOs - namely to hold
* common CRUD methods that they might all use. You should only need to extend
* this class when your require custom CRUD logic.
* <p/>
* <p>
* To register this class in your Spring context file, use the following XML.
*
* <pre>
*      &lt;bean id="fooDao" class="org.dudu.core.dao.hibernate.GenericDaoHibernate"&gt;
*          &lt;constructor-arg value="org.dudu.core.model.Foo"/&gt;
*      &lt;/bean&gt;
* </pre>
*
* @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
* @param <T>
*            a type variable
* @param <PK>
*            the primary key for that type
*/
@Repository("genericDao")
public class GenericDaoHibernate<T extends VgEntity, PK extends Serializable> extends HibernateDaoSupport implements
    GenericDao<T, PK> {
  /**
   * Log variable for all child classes. Uses LogFactory.getLog(getClass())
   * from Commons Logging
   */
  protected final Log log = LogFactory.getLog(getClass());
  private Class<T> persistentClass =
      ReflectionUtils.getSuperClassGenricType(getClass());
  private HibernateTemplate hibernateTemplate;
//  @Resource(name = "sessionFactory")
//  private SessionFactory sessionFactory;
 
 
 
    protected SessionFactory sessionFactory;
   
    @Resource(name = "sessionFactory")
    protected void setSuperSessionFactory(SessionFactory sessionFactory){ 
        super.setSessionFactory(sessionFactory);
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
   
   
    protected SessionFactory getSuperSessionFactory() {
        return sessionFactory;
    }
   
    protected Session getSession(SessionFactory sessionFactory)
      throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    session.setFlushMode(FlushMode.AUTO);
    return session;
  }

  /**
   * Constructor that takes in a class to see which type of entity to persist.
   * Use this constructor when subclassing.
   *
   * @param persistentClass
   *            the class type you'd like to persist
   */
 
//  public GenericDaoHibernate(final Class<T> persistentClass) {
//    this.persistentClass = persistentClass;
//  }

  /**
   * Constructor that takes in a class and sessionFactory for easy creation of
   * DAO.
   *
   * @param persistentClass
   *            the class type you'd like to persist
   * @param sessionFactory
   *            the pre-configured Hibernate SessionFactory
   */
//  public GenericDaoHibernate(final Class<T> persistentClass,
//      SessionFactory sessionFactory) {
//    this.persistentClass = persistentClass;
//    this.sessionFactory = sessionFactory;
//    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
//  }

//  public HibernateTemplate getHibernateTemplate() {
//    return this.hibernateTemplate;
//  }
//
//  public SessionFactory getSessionFactory() {
//    return this.sessionFactory;
//  }
//
//  @Resource(name = "sessionFactory")
//  public void setSessionFactory(SessionFactory sessionFactory) {
//    this.sessionFactory = sessionFactory;
//    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
//  }

  /**
   * {@inheritDoc}
   */
  public List<T> getAll() {
    return hibernateTemplate.loadAll(this.persistentClass);
  }

  /**
   * {@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  public List<T> getAllDistinct() {
    Collection result = new LinkedHashSet(getAll());
    return new ArrayList(result);
  }

  /**
   * {@inheritDoc}
   */
  public T get(PK id) {
    T entity = null;
    try
    {
      entity = (T) hibernateTemplate.get(this.persistentClass, id);
    }
    catch(Exception e)
    {
      log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
      + id + "' not found..." + e);
    }
   
//    if (entity == null) {
//      log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
//          + id + "' not found...");
//      throw new ObjectRetrievalFailureException(this.persistentClass, id);
//    }

    return entity;
  }

  /**
   * {@inheritDoc}
   */
  public boolean exists(PK id) {
    T entity = (T) hibernateTemplate.get(this.persistentClass, id);
    return entity != null;
  }

  /**
   * {@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  public List<T> findByNamedQuery(String queryName,
      Map<String, Object> queryParams) {
    String[] params = new String[queryParams.size()];
    Object[] values = new Object[queryParams.size()];

    int index = 0;
    for (String s : queryParams.keySet()) {
      params[index] = s;
      values[index++] = queryParams.get(s);
    }

    return hibernateTemplate.findByNamedQueryAndNamedParam(queryName,
        params, values);
  }

  /********************** DB DML methods start**************************/
  /**
   * {@inheritDoc}
   */
  public T save(T object) {
    return (T) hibernateTemplate.merge(object);
  }

  /**
   * {@inheritDoc}
   */
  public void remove(PK id) {
    hibernateTemplate.delete(this.get(id));
  }

  @Override
  public void delete(T entity) {
    this.getHibernateTemplate().delete(entity);
  }

  @Override
  public void deleteAll(Collection<T> entities) {
    this.getHibernateTemplate().deleteAll(entities);
  }

  @Override
  public void store(T entity) {
    this.getHibernateTemplate().saveOrUpdate(entity);
  }

  /********************** end DML methods **************************/

  /********************* springside methods start******************************/
  /**
   * 取得当前Session.
   */
//  public Session getSession() {
//    return sessionFactory.getCurrentSession();
//  }

  /**
   * 获取全部对象, 支持按属性行序.
   */

  @SuppressWarnings("unchecked")
  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);
  }

  /**
   * 按属性查找唯一对象, 匹配方式为相等.
   */
  @SuppressWarnings("unchecked")
  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
   *            数量可变的参数,按顺序绑定.
   */
  @SuppressWarnings("unchecked")
  public <X> List<X> find(final String hql, final Object... values) {
    return createQuery(hql, values).list();
  }

  /**
   * 按HQL查询对象列表.
   *
   * @param values
   *            命名参数,按名称绑定.
   */
  @SuppressWarnings("unchecked")
  public <X> List<X> find(final String hql, final Map<String, ?> values) {
    return createQuery(hql, values).list();
  }

  /**
   * 按HQL查询唯一对象.
   *
   * @param values
   *            数量可变的参数,按顺序绑定.
   */
  @SuppressWarnings("unchecked")
  public <X> X findUnique(final String hql, final Object... values) {
    return (X) createQuery(hql, values).uniqueResult();
  }

  /**
   * 按HQL查询唯一对象.
   *
   * @param values
   *            命名参数,按名称绑定.
   */
  @SuppressWarnings("unchecked")
  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.
   */
  @SuppressWarnings("unchecked")
  public List<T> find(final Criterion... criterions) {
    return createCriteria(criterions).list();
  }

  /**
   * 按Criteria查询唯一对象.
   *
   * @param criterions
   *            数量可变的Criterion.
   */
  @SuppressWarnings("unchecked")
  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(persistentClass);
    for (Criterion c : criterions) {
      criteria.add(c);
    }
    return criteria;
  }

  /**
   * 初始化对象. 使用load()方法得到的仅是对象Proxy, 在传到View层前需要进行初始化. 如果传入entity,
   * 则只初始化entity的直接属性,但不会初始化延迟加载的关联集合和属性. 如需初始化关联属性,需执行:
   * Hibernate.initialize(user.getRoles()),初始化User的直接属性和关联集合.
   * Hibernate.initialize
   * (user.getDescription()),初始化User的直接属性和延迟加载的Description属性.
   */
  public void initProxyObject(Object proxy) {
    Hibernate.initialize(proxy);
  }

  /**
   * Flush当前Session.
   */
  public void flush() {
    getSession().flush();
  }

  /**
   * 为Query添加distinct transformer. 预加载关联对象的HQL会引起主对象重复, 需要进行distinct处理.
   */
  public Query distinct(Query query) {
    query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return query;
  }

  /**
   * 为Criteria添加distinct transformer. 预加载关联对象的HQL会引起主对象重复, 需要进行distinct处理.
   */
  public Criteria distinct(Criteria criteria) {
    criteria
        .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return criteria;
  }

  /**
   * 取得对象的主键名.
   */
  public String getIdName() {
    ClassMetadata meta = getSessionFactory().getClassMetadata(
        persistentClass);
    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);
  }

  // -- 分页查询函数 --//

  /**
   * 分页获取全部对象.
   */
  public WPage<T> getAll(final WPage<T> WPage) {
    return findWPage(WPage);
  }

  /**
   * 按HQL分页查询.
   *
   * @param WPage
   *            分页参数. 注意不支持其中的orderBy参数.
   * @param hql
   *            hql语句.
   * @param values
   *            数量可变的查询参数,按顺序绑定.
   *
   * @return 分页查询结果, 附带结果列表及所有查询输入参数.
   */
  @SuppressWarnings("unchecked")
  public WPage<T> findWPage(final WPage<T> WPage, final String hql,
      final Object... values) {
    Assert.notNull(WPage, "WPage不能为空");

    Query q = createQuery(hql, values);

    if (WPage.isAutoCount()) {
      long totalCount = countHqlResult(hql, values);
      WPage.setTotalCount(totalCount);
    }

    setWPageParameterToQuery(q, WPage);

    List result = q.list();
    WPage.setResult(result);
    return WPage;
  }

  /**
   * 按HQL分页查询.
   *
   * @param WPage
   *            分页参数. 注意不支持其中的orderBy参数.
   * @param hql
   *            hql语句.
   * @param values
   *            命名参数,按名称绑定.
   *
   * @return 分页查询结果, 附带结果列表及所有查询输入参数.
   */
  @SuppressWarnings("unchecked")
  public WPage<T> findWPage(final WPage<T> WPage, final String hql,
      final Map<String, ?> values) {
    Assert.notNull(WPage, "WPage不能为空");

    Query q = createQuery(hql, values);

    if (WPage.isAutoCount()) {
      long totalCount = countHqlResult(hql, values);
      WPage.setTotalCount(totalCount);
    }

    setWPageParameterToQuery(q, WPage);

    List result = q.list();
    WPage.setResult(result);
    return WPage;
  }

  /**
   * 按Criteria分页查询.
   *
   * @param WPage
   *            分页参数.
   * @param criterions
   *            数量可变的Criterion.
   *
   * @return 分页查询结果.附带结果列表及所有查询输入参数.
   */
  @SuppressWarnings("unchecked")
  public WPage<T> findWPage(final WPage<T> WPage, final Criterion... criterions) {
    Assert.notNull(WPage, "WPage不能为空");

    Criteria c = createCriteria(criterions);

    if (WPage.isAutoCount()) {
      int totalCount = countCriteriaResult(c);
      WPage.setTotalCount(totalCount);
    }

    setWPageParameterToCriteria(c, WPage);

    List result = c.list();
    WPage.setResult(result);
    return WPage;
  }

  /**
   * 设置分页参数到Query对象,辅助函数.
   */
  protected Query setWPageParameterToQuery(final Query q, final WPage<T> WPage) {

    Assert
        .isTrue(WPage.getPageSize() > 0,
            "WPage Size must larger than zero");

    // hibernate的firstResult的序号从0开始
    q.setFirstResult(WPage.getFirst() - 1);
    q.setMaxResults(WPage.getPageSize());
    return q;
  }

  /**
   * 设置分页参数到Criteria对象,辅助函数.
   */
  protected Criteria setWPageParameterToCriteria(final Criteria c,
      final WPage<T> WPage) {

    Assert
        .isTrue(WPage.getPageSize() > 0,
            "WPage Size must larger than zero");

    // hibernate的firstResult的序号从0开始
    c.setFirstResult(WPage.getFirst() - 1);
    c.setMaxResults(WPage.getPageSize());

    if (WPage.isOrderBySetted()) {
      String[] orderByArray = StringUtils.split(WPage.getOrderBy(), ',');
      String[] orderArray = StringUtils.split(WPage.getOrder(), ',');

      Assert.isTrue(orderByArray.length == orderArray.length,
          "分页多重排序参数中,排序字段与排序方向的个数不相等");

      for (int i = 0; i < orderByArray.length; i++) {
        if (WPage.ASC.equals(orderArray[i])) {
          c.addOrder(Order.asc(orderByArray[i]));
        } else {
          c.addOrder(Order.desc(orderByArray[i]));
        }
      }
    }
    return c;
  }

  /**
   * 执行count查询获得本次Hql查询所能获得的对象总数.
   *
   * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
   */
  protected long countHqlResult(final String hql, final Object... values) {
    String countHql = prepareCountHql(hql);

    try {
      Long count = findUnique(countHql, values);
      return count;
    } catch (Exception e) {
      throw new RuntimeException("hql can't be auto count, hql is:"
          + countHql, e);
    }
  }

  /**
   * 执行count查询获得本次Hql查询所能获得的对象总数.
   *
   * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
   */
  protected long countHqlResult(final String hql, final Map<String, ?> values) {
    String countHql = prepareCountHql(hql);

    try {
      Long count = findUnique(countHql, values);
      return count;
    } catch (Exception e) {
      throw new RuntimeException("hql can't be auto count, hql is:"
          + countHql, e);
    }
  }

  private String prepareCountHql(String orgHql) {
    String fromHql = orgHql;
    // select子句与order by子句会影响count查询,进行简单的排除.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;
    return countHql;
  }

  /**
   * 执行count查询获得本次Criteria查询所能获得的对象总数.
   */
  @SuppressWarnings("unchecked")
  protected int countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    // 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
      orderEntries = (List) ReflectionUtils.getFieldValue(impl,
          "orderEntries");
      ReflectionUtils
          .setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
      log.error("不可能抛出的异常:" + e.getMessage());
    }

    // 执行Count查询
    Integer totalCountObject = (Integer) c.setProjection(
        Projections.rowCount()).uniqueResult();
    int totalCount = (totalCountObject != null) ? totalCountObject : 0;

    // 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
    c.setProjection(projection);

    if (projection == null) {
      c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }
    if (transformer != null) {
      c.setResultTransformer(transformer);
    }
    try {
      ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
    } catch (Exception e) {
      log.error("不可能抛出的异常:" + e.getMessage());
    }

    return totalCount;
  }

  // -- 属性过滤条件(PropertyFilter)查询函数 --//

  /**
   * 按属性查找对象列表,支持多种匹配方式.
   *
   * @param matchType
   *            匹配方式,目前支持的取值见PropertyFilter的MatcheType enum.
   */
  public List<T> findBy(final String propertyName, final Object value,
      final MatchType matchType) {
    Criterion criterion = buildCriterion(propertyName, value, matchType);
    return find(criterion);
  }

  /**
   * 按属性过滤条件列表查找对象列表.
   */
  public List<T> find(List<PropertyFilter> filters) {
    Criterion[] criterions = buildCriterionByPropertyFilter(filters);
    return find(criterions);
  }

  /**
   * 按属性过滤条件列表分页查找对象.
   */
  public WPage<T> findWPage(final WPage<T> WPage,
      final List<PropertyFilter> filters) {
    Criterion[] criterions = buildCriterionByPropertyFilter(filters);
    return findWPage(WPage, criterions);
  }

  /**
   * 按属性条件参数创建Criterion,辅助函数.
   */
  protected Criterion buildCriterion(final String propertyName,
      final Object propertyValue, final MatchType matchType) {
    Assert.hasText(propertyName, "propertyName不能为空");
    Criterion criterion = null;
    // 根据MatchType构造criterion
    switch (matchType) {
    case EQ:
      criterion = Restrictions.eq(propertyName, propertyValue);
      break;
    case LIKE:
      criterion = Restrictions.like(propertyName, (String) propertyValue,
          MatchMode.ANYWHERE);
      break;

    case LE:
      criterion = Restrictions.le(propertyName, propertyValue);
      break;
    case LT:
      criterion = Restrictions.lt(propertyName, propertyValue);
      break;
    case GE:
      criterion = Restrictions.ge(propertyName, propertyValue);
      break;
    case GT:
      criterion = Restrictions.gt(propertyName, propertyValue);
    }
    return criterion;
  }

  /**
   * 按属性条件列表创建Criterion数组,辅助函数.
   */
  protected Criterion[] buildCriterionByPropertyFilter(
      final List<PropertyFilter> filters) {
    List<Criterion> criterionList = new ArrayList<Criterion>();
    for (PropertyFilter filter : filters) {
      if (!filter.hasMultiProperties()) { // 只有一个属性需要比较的情况.
        Criterion criterion = buildCriterion(filter.getPropertyName(),
            filter.getMatchValue(), filter.getMatchType());
        criterionList.add(criterion);
      } else {// 包含多个属性需要比较的情况,进行or处理.
        Disjunction disjunction = Restrictions.disjunction();
        for (String param : filter.getPropertyNames()) {
          Criterion criterion = buildCriterion(param, filter
              .getMatchValue(), filter.getMatchType());
          disjunction.add(criterion);
        }
        criterionList.add(disjunction);
      }
    }
    return criterionList.toArray(new Criterion[criterionList.size()]);
  }

  /********************* end springside methods ******************************/

  /********************** start expand methods **************************/

  @Override
  @SuppressWarnings("unchecked")
  public int executeByHql(final String hql, final String[] paramNames,
      final Object[] values) {
    return (Integer) this.getHibernateTemplate().execute(
        new HibernateCallback() {
          public Object doInHibernate(Session session)
              throws HibernateException, SQLException {
            Query query = session.createQuery(hql);
            if (values != null) {
              for (int i = 0; i < paramNames.length; i++) {
                if (StringUtils.isEmpty(paramNames[i]))
                  continue;
                if (values[i] != null
                    && (Collection.class
                        .isAssignableFrom(values[i]
                            .getClass()))) {
                  query.setParameterList(paramNames[i],
                      (Collection) values[i]);
                } else {
                  query
                      .setParameter(paramNames[i],
                          values[i]);
                }
              }
            }
            return query.executeUpdate();
          }
        });
  }

  @Override
  public int executeByHql(String hql, String parameterKey, Object value) {
    return executeByHql(hql, new String[] { parameterKey },
        new Object[] { value });
  }

  @SuppressWarnings("unchecked")
  public List findByQuery(String hql, String parameterKey, Object value) {
    return findByQuery(hql, new String[] { parameterKey },
        new Object[] { value });
  }

  @SuppressWarnings("unchecked")
  public List findByQuery(String hql) {
    return findByQuery(hql, new String[0], new Object[0]);
  }

  @SuppressWarnings("unchecked")
  public List findByQuery(final String hql, final String[] paramNames,
      final Object[] values) {
    return (List) this.getHibernateTemplate().execute(
        new HibernateCallback() {

          public Object doInHibernate(Session session)
              throws HibernateException, SQLException {

            Query query = session.createQuery(hql);
            if (values != null) {
              for (int i = 0; i < paramNames.length; i++) {
                if (StringUtils.isEmpty(paramNames[i]))
                  continue;
                if (values[i] != null
                    && (Collection.class
                        .isAssignableFrom(values[i]
                            .getClass()))) {
                  query.setParameterList(paramNames[i],
                      (Collection) values[i]);
                } else {
                  query
                      .setParameter(paramNames[i],
                          values[i]);
                }
              }
            }
            return query.list();
          }
        });
  }

  @SuppressWarnings("unchecked")
  public Object findByQueryUniqueResult(final String hql,
      final String[] paramNames, final Object[] values) {
    return this.getHibernateTemplate().execute(new HibernateCallback() {

      public Object doInHibernate(Session session)
          throws HibernateException, SQLException {
        Query query = session.createQuery(hql);
        if (values != null) {
          for (int i = 0; i < paramNames.length; i++) {
            if (StringUtils.isEmpty(paramNames[i]))
              continue;
            if (values[i] != null
                && (Collection.class.isAssignableFrom(values[i]
                    .getClass()))) {
              query.setParameterList(paramNames[i],
                  (Collection) values[i]);
            } else {
              query.setParameter(paramNames[i], values[i]);
            }
          }
        }
        return query.uniqueResult();
      }
    });
  }

  @Override
  public Object findByQueryUniqueResult(String hql, String parameterKey,
      Object value) {
    return findByQueryUniqueResult(hql, new String[] { parameterKey },
        new Object[] { value });
  }

  @Override
  @SuppressWarnings("unchecked")
  public WPage<T> findWPageExpand(final WPage<T> WPage, final String hql,
      final Map<String, ?> values) {
    Assert.notNull(WPage, "WPage不能为空");
    // System.out.println("before_hql : "+hql);
    Query q = createQuery(hql, values);
    if (WPage.isAutoCount()) {
      Long totalCount = countHqlResultExpand(hql, values);
      WPage.setTotalCount(totalCount);
    }
    setWPageParameterToQuery(q, WPage);
    List result = q.list();
    WPage.setResult(result);
    return WPage;
  }

  @Override
  public WPage<T> findWPageExpand(final WPage<T> WPage, final String hql) {
    return findWPageExpand(WPage, hql, null);
  }

  @Override
  public T get(Class<T> clazz, Long id) {
    return (T) this.getHibernateTemplate().get(clazz, id);
  }

  @Override
  public void initialize(Object object) {
    this.getHibernateTemplate().initialize(object);
  }

  @Override
  public T load(Class<T> clazz, Long id) {
    return (T) this.getHibernateTemplate().get(clazz, id);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<T> loadAll(final Class<T> clazz, final Long[] entityIds) {
    return (List<T>) this.getHibernateTemplate().execute(
        new HibernateCallback() {
          public Object doInHibernate(Session session)
              throws HibernateException {
            Criteria criteria = session.createCriteria(clazz).add(
                Expression.in("id", entityIds));
            return criteria.list();
          }
        });
  }

  @Override
  public List<T> loadAll(Class<T> clazz) {
    return this.getHibernateTemplate().loadAll(clazz);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<T> loadAll(final Class<T> clazz, final List<Long> ids) {
    return (List<T>) this.getHibernateTemplate().execute(
        new HibernateCallback() {
          public Object doInHibernate(Session session)
              throws HibernateException {
            Criteria criteria = session.createCriteria(clazz).add(
                Expression.in("id", ids));
            return criteria.list();
          }
        });
  }

  @Override
  @SuppressWarnings("unchecked")
  public List query(final String hql, final Map params) {
    return (List) this.getHibernateTemplate().execute(
        new HibernateCallback() {

          public Object doInHibernate(Session session)
              throws HibernateException, SQLException {

            Query query = session.createQuery(hql);
            for (Iterator i = params.keySet().iterator(); i
                .hasNext();) {
              String key = (String) i.next();
              Object value = params.get(key);
              query.setParameter(key, value);
            }
            return query.list();
          }
        });
  }

  @Override
  public void refresh(Object object) {
    this.getHibernateTemplate().lock(object, LockMode.READ);
  }

  protected Long countHqlResultExpand(final String hql,
      final Map<String, ?> values) {
    String countHql = prepareCountHqlExpand(hql);
    // System.out.println("after_hql:"+countHql);
    try {
      Long count = findUnique(countHql, values);
      return count;
    } catch (Exception e) {
      throw new RuntimeException("hql can't be auto count, hql is:"
          + countHql, e);
    }
  }

  private String prepareCountHqlExpand(String orgHql) {
    String fromHql = orgHql;
    // fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    // fromHql = StringUtils.substringBefore(fromHql, "order by");
    String countHql = " select count (*) "
        + removeSelect(removeOrders(fromHql));
    // String countHql = " select count(*) " + fromHql;
    return countHql;
  }

  private static String removeSelect(String hql) {
    Assert.hasText(hql);
    int beginPos = hql.toLowerCase().indexOf("from");
    Assert.isTrue(beginPos != -1, " hql : " + hql
        + " must has a keyword 'from'");
    return hql.substring(beginPos);
  }

  private static String removeOrders(String hql) {
    Assert.hasText(hql);
    Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*",
        Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(hql);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      m.appendReplacement(sb, "");
    }
    m.appendTail(sb);
    return sb.toString();
  }
  /********************** end expand methods **************************/
TOP

Related Classes of com.wizriver.dao.GenericDaoHibernate

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.