Hibernate(JPA ) 查詢返回只有一個字段,返回類型設置為List,取值報錯

問題: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 );

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。