我有一個資料庫表 Cars,每一行代表一個不同的汽車型號,有不同的 id、brand、model_name 和數量。我想使用 Hibernate 撰寫一個查詢,以按品牌獲取最受歡迎汽車的數量,例如 - 在 DB 5 Volkswagen Polo、3 Volkswagen Tiguan、4 Skoda Octavia、8 Skoda Rapid,我想要一個結果: 大眾 : 5 斯柯達 : 8
這是我的查詢:
@Query(value = "SELECT brand, MAX(amount) FROM cars GROUP BY brand ORDER BY amount DESC", nativeQuery = true)
List<Car> getAmountOfMostPopularCarsByBrand();
界面 Car 看起來像這樣:
interface Car {
String getBrand();
Long getAmount();
}
該查詢在 IntelliJ 中運行良好,它帶來了預期的結果,但是當我嘗試在應用程式中使用它時:
List<Car> cars = getAmountOfMostPopularCarsByBrand()
我得到了具有良好“品牌”欄位的物件串列,但“金額”欄位為空,它只是沒有正確映射(翻譯)。知道如何解決嗎?
uj5u.com熱心網友回復:
我認為您需要使用別名MAX(amount):
@Query(value = "SELECT brand, MAX(amount) as amount FROM cars GROUP BY brand ORDER BY amount DESC", nativeQuery = true)
我認為轉換器會在查詢結果中查找與類中屬性名稱匹配的標頭。
您的查詢將回傳帶有標題的結果brand | MAX(amount),我的將有正確的:brand | amount。
除此之外,這兩個查詢是相同的。
uj5u.com熱心網友回復:
通過自己映射解決了這個問題,所以查詢方法回傳:
@Query(value = "SELECT brand, MAX(amount) as amount FROM cars GROUP BY brand ORDER BY amount DESC", nativeQuery = true)
List<Object> getAmountOfMostPopularCarsByBrand();
然后我可以這樣做:
Collection cars = getAmountOfMostPopularCarsByBrand()
.stream()
.map(c -> return new Car((String)c[0], (long)c[1]))
.collect(Collectors.toList()));;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497664.html
下一篇:什么導致java.lang.IllegalStateException:FailedtoloadApplicationContext錯誤?
