hibernate基础工具findBySQL学习
生活随笔
收集整理的這篇文章主要介紹了
hibernate基础工具findBySQL学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public List<Map<String,Object>> findBySQL(String sql,Map<String,Object> param,int start,int max) {log.debug("finding List by hql");try {
//最后返回map map的key可為別名和數據庫字段SQLQuery query=sessionFactory.getCurrentSession().createSQLQuery(sql);query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);//遍歷param插入參數if(param!=null) {for (Map.Entry<String, Object> entry : param.entrySet()) {Object obj = entry.getValue(); //這里考慮傳入的參數是什么類型,不同類型使用的方法不同 hibernate傳入list的方法if(obj instanceof Collection<?>){ query.setParameterList(entry.getKey(), (Collection<?>)obj); }else if(obj instanceof Object[]){ query.setParameterList(entry.getKey(), (Object[])obj); }else{ query.setParameter(entry.getKey(), obj); } }}query.setFirstResult(start);//起始頁if(max!=0){query.setMaxResults(max);//每頁幾條}List<Map<String,Object>> results = query.list();log.debug("find list successful, result size: " + results.size());return results;} catch (RuntimeException re) {log.error("find list failed", re);throw re;}}
數組傳入需要為封裝類
//最后返回map map的key可為別名和數據庫字段SQLQuery query=sessionFactory.getCurrentSession().createSQLQuery(sql);query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);//遍歷param插入參數if(param!=null) {for (Map.Entry<String, Object> entry : param.entrySet()) {Object obj = entry.getValue(); //這里考慮傳入的參數是什么類型,不同類型使用的方法不同 hibernate傳入list的方法if(obj instanceof Collection<?>){ query.setParameterList(entry.getKey(), (Collection<?>)obj); }else if(obj instanceof Object[]){ query.setParameterList(entry.getKey(), (Object[])obj); }else{ query.setParameter(entry.getKey(), obj); } }}query.setFirstResult(start);//起始頁if(max!=0){query.setMaxResults(max);//每頁幾條}List<Map<String,Object>> results = query.list();log.debug("find list successful, result size: " + results.size());return results;} catch (RuntimeException re) {log.error("find list failed", re);throw re;}}
注意 數組傳入時是int 是沒有屬于
Object[] 或者 Collection<?>數組傳入需要為封裝類
轉載于:https://www.cnblogs.com/L-a-u-r-a/p/7050001.html
總結
以上是生活随笔為你收集整理的hibernate基础工具findBySQL学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实战-130W表增加字段耗时
- 下一篇: 微信小程序-智能机器人