本人在實際工作中使用Spring Data Jpa框架時,一般查詢結果只返回對應的Entity實體。但有時根據實際業務,需要進行一些較復雜的查詢,比較棘手。雖然在框架上我們可以使用@Query注解執行我們自定義的sql語句,但是其返回值為List<Object[]> 類型,即多個Object數組的List集合,然后通過解析獲取需要的數據,比較麻煩。
於是,開始考慮能否將查詢結果返回至自定義的實體類,網上尋找解決方案並自己不斷實踐,遇到一些問題,跟大家分享下。
首先,介紹一種可行的方案:
1、自定義實體
-
/**
-
* Created by administor on 2018-7-18 17:50.
-
*/
-
public
class CarTraceResult {
-
private String plateNo;
-
private Integer plateColor;
-
private String typeName;
-
private String parkName;
-
private Calendar time;
-
private
Long times;
-
-
public CarTraceResult(String plateNo, Integer plateColor, String typeName, String parkName, Calendar time,
Long times) {
-
this.plateNo = plateNo;
-
this.plateColor = plateColor;
-
this.typeName = typeName;
-
this.parkName = parkName;
-
this.time = time;
-
this.times = times;
-
}
-
-
//省略get、set方法
-
}
CarTraceResult需要實現構造方法,因為后面會用到。
2、查詢
-
-
@Query(value = "
select
new com.park.carTrace.pojo.CarTraceResult(a.plateNo, a.plateColor, a.typeName, a.parkName,
max(a.time)
as
time,
count(a.id)
as times)
" +
-
"
from CarTraceRecordEntity a
where a.plateNo = ?
1
and a.plateColor = ?
2
" +
-
"
and a.type = ?
3
group
by a.parkNo
order
by
time
desc
")
-
List<CarTraceResult> queryCarTraceRecord(String plateNo, Integer plateColor, Integer type);
網友有強調自定義實體類的屬性和名稱要與查詢結果完全對應,那么問題來了,由於我使用了max()和count()函數,並分別將對應結果起了別名,該語句在執行中是報錯的。到這里,似乎是無解了。反復嘗試后,大膽將代碼改為:
-
@Query(value = "
select
new com.park.carTrace.pojo.CarTraceResult(a.plateNo, a.plateColor, a.typeName, a.parkName,
max(a.time),
count(a.id))
" +
-
"
from CarTraceRecordEntity a
where a.plateNo = ?
1
and a.plateColor = ?
2
" +
-
"
and a.type = ?
3
group
by a.parkNo
order
by
time
desc
")
-
List<CarTraceResult> queryCarTraceRecord(String plateNo, Integer plateColor, Integer type);
去掉了后面兩個的別名,結果程序成功執行並返回了結果,如圖:
總結:
1、查詢中CustomModel最好寫全路徑,程序有可能無法定位到該類。
2、自定義的實體類屬性只需要順序和數據類型與查詢結果對應即可,名字無需一致,當然一般也把名字對應起來方便閱讀。
3、查詢結果實際上還是返回的List<Object[]> 類型,只不過是按照數據類型和順序,對應到自定義的實體里去了。即便如此,該方案也為我們的工作提供了方便。
最后,希望本文能對需要的朋友有所幫助,不足之處請斧正。
原文地址:https://blog.csdn.net/liuyunyihao/article/details/81106799