[英]Spring Data returning List<Object[]>
我有這個存儲庫:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>{
@Query("SELECT p.textToSearch as text, count(*) as counter FROM Product p GROUP BY text_to_search ORDER BY counter DESC")
List<TopProductDTO> findTopProducts();
}
TopProductDTO類的位置是:
public class TopProductDTO {
public TopProductDTO() {}
private String text;
private Integer counter;
// Getters and Setters are omited
}
但是當我執行代碼時
List<TopProductDTO> topProducts = productRepository.findTopProducts();
它返回一個
List<Object[]> insted a List<TopProductDTO>
就像每列都是列表中對象數組的索引一樣...... Spring Data是否應該將查詢中的'text'和'counter'列與TopProductDTO中的字段綁定?
結果我的Thymeleaf模板中出現了這個錯誤:
00:37:22.659 [http-nio-8080-exec-5] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "topProductDTO.text" (products/top:46)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 14): Property or field 'text' cannot be found on object of type 'java.lang.Object[]' - maybe not public?
我正在使用Spring Boot 1.3.3和Postgres 9.2
嘗試使用DTO的構造函數。
聲明一個新的構造函數
public TopProductDTO(String text, Integer count) {
this.text = text;
this.count = count;
}
在您的查詢中使用新的構造函數
@Query("SELECT new TopProductDTO(p.textToSearch, count(id))FROM Product p GROUP BY text_to_search ORDER BY counter DESC")
List<TopProductDTO> findTopProducts();
}
使用班級的完全限定名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.