Hibernate中运用doInHibernate 构造公用findByhql(查询)和updateByHql(修改)方法

在hibernate中,运用doInHibernate,避免了手动open session和close session ,减少了一系列session关闭的麻烦。

公用的setParameter 方法,下面有调用,传入一个query 实例,和Map<String, Object> map 类型的参数

 private void setParameter(Query query, Map<String, Object> map) {
  if (map != null && !map.isEmpty()) {
   Set<String> keySet = map.keySet();
   for (String string : keySet) {
    Object obj = map.get(string);
    // 这里考虑传入的参数是什么类型,不同类型使用的方法不同
    if (obj instanceof Collection<?>) {
     query.setParameterList(string, (Collection<?>) obj);
    } else if (obj instanceof Object[]) {
     query.setParameterList(string, (Object[]) obj);
    } else {
     query.setParameter(string, obj);
    }
   }
  }
 }

updateByHql:

public void updateByHql(final String hql, final Map<String, Object> map) throws Exception {
  template.execute(new HibernateCallback() {
      @Override
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
         Query query = session.createQuery(hql);

        //调用set参数的方法
         setParameter(query, map);
         query.executeUpdate();
         return null;
         }

      });

    }

 findByHql:

 public List<Object> findByHql(final String hql, final Map<String, Object> map) throws Exception {
  return (List<Object>) template.execute(new HibernateCallback() {
   public List<Object> doInHibernate(final Session session) throws HibernateException, SQLException {

    Query query = session.createQuery(hql);
    setParameter(query, map);
    /*
     * StringBuffer sb = new StringBuffer(); Query query0 =
     * session.createSQLQuery(sb.toString());//<STRONG>执行普通sql</STRONG> Query query1 =
     * session.createQuery(sb.toString());// <STRONG>执行hql </STRONG>
     */

    return query.list();
   }
  });
 }

调用例子:

String hql = "from ABC where bb = :aa";
  Map<String, Object> map = new HashMap<String, Object>();

  map.put("aa", 22);

  List<Object> cList = commonDao.findByHql(hql, map);
  if (cList == null || cList.size() == 0)
   return null;
  else
   return (ABC) cList.get(0);

update类似与query,只是没有返回参数

相关推荐