问题:Hibernate(JPA ) 查询返回只有一个字段,返回类型设置为List<object []>时,根据需求需要把object数组的第一个值转为Integer类型(查询回来的是Long类型),然后无论用result.get(0).toString()还是result.get(0)[0].toString()都报错,
错误代码:
@Query("select count(t.id) from TxxItem t where t.invest >= ?2 and t.parentCode like ?1 and t.itemtype like ?3 ") public List< Object[]> getCountyYiCount(String parentCode,Double invest ,String category);
这个查询只返回一个字段,正常使用 result.get(0)已经拿到了Object对象,在debug时用result.get(0)可以拿到返回值,是Long,然后需要把值转为Integer类型,result.get(0).toString()、result.get(0)[0].toString()都报错,前者在expression中可以取到值,后者直接报错。
原因:
查询结果表明:如果查询一个字段时返回的数据实际是List<Object>类型,这和List<Object[]>不匹配了。
如果查询返回多个字段的数据时返回类型则是List<Object[]>
解决:
1.查询返回一个字段数据时,返回类型设置为List<Object>
@Query("select count(t.id) from TxxItem t where t.invest >= ?2 and t.parentCode like ?1 and t.itemtype like ?3 ") public List< Object> getCountyYiCount(String parentCode,Double invest ,String category);
2.查询返回多个字段时,返回类型设为List<object []>
@Query("select t.itemtype, count(t.id) from TxxItem t where t.parentCode like ?1 and t.state='1' group by t.itemtype ") public List< Object[]> getFaciCount(String parentCode );