通常hibernate查询出的结果集是类似于 List<T> 或 List<Object[]> 的类型
类似于下面这个方法
public List<SfJmsfT> getChosePayList(SfJmsfT jmsf) { List list = new ArrayList(); StringBuilder hql = new StringBuilder(); hql.append("From SfJmsfT where zf = 0 and yhbh=? and czbh=?"); List<SfJmsfT> result = null; try { result = this.executeHqlList(hql.toString(), new Object[]{jmsf.getYhbh(),jmsf.getCzbh()}); } catch (BDXCException e) { e.printStackTrace(); logger.error(BDXCUtil.getExceptionString(e)); } return result; }
其实hibernate可以查询出List<Map<String,Object>>类型的结果集。现简单代码描述
语句1
// 结果list中,每条记录对应一个object数组,object[]中每个元素为hql语句中列的序号(从0开始)。 String hql=“select s.name from Student s”; List ls=session.createQuery(hql).list(); for(String obj[]:ls){ System.out.pringln(obj[0]); }
语句2
//结果list中,每条记录对应一个map,map中key为hql语句中的序号,从0开始,key为字符,非数字。 String hql=“select new map(s.name) from Student s”; List ls=session.createQuery(hql).list(); for(Map m:ls){ System.out.pringln(m.get("0")); }
语句3
//结果list中,每条记录对应一个map,map中key为hql语句中的别名。 String hql=“select new map(s.name as name) from Student s”; List ls=session.createQuery(hql).list(); for(Map m:ls){ System.out.pringln(m.get("name")); }
hibernate对 select new map类型的hql解析的时候,遇到map这个关键字,将后面的列作为值,别名作为键(若无别名,则用数字代替)存入到一个HashMap中。
方法中使用该类型hql
public String getThirdPayList(BDXCPageContext context, SfJmsfT queryVo) { List list = new ArrayList(); // 根据queryVo对象转换查询条件 String sql = "SELECT COUNT(yhbh) FROM sf_jmsf_t WHERE zf=‘0‘ and jffs=‘银行‘ "; sql=sqlPingjie(sql,queryVo); Long num = serialBillDao.getThirdPayListCount(sql, list.toArray()); context.setTotalNum(num.intValue()); String hql = " select new map(bh as bh,yhbh as yhbh,cnq as cnq,fylb as fylb ," + "jfrq as jfrq,jfje as jfje,zkje as zkje,czbh as czbh,lsh as lsh ,jffs as jffs ," + "czy as czy) FROM SfJmsfT WHERE zf=‘0‘ "; hql=sqlPingjie(hql,queryVo); List result = serialBillDao.getThirdPayList(hql, list, context); String msg = BDXCUtil.createJsonStr(context.getTotalNum(), result); return msg; }
附:select new ***类型解释
select new List(p.name, p.address) from Person as p ; --select将选择出来的属性存入一个List对象中
select new ClassTest(p.name, p.address) from Person as p; --select将选择出来的属性封装成对象,前提是ClassTest支持p.name, p.address的构造函数,
select new Map(p.name as personName) from Person as p ; --select将选中的表达式命名为别名,这种用法与new Map()结合,选择出来的是Map结构, 以personName为key,将实际选择出来的值作为value
时间: 2024-10-12 20:49:52