postgresql Spring Data 返回 List<Object[]>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35714245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data returning List<Object[]>
提问by Vitor Vezani
I have this repository:
我有这个存储库:
@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();
}
where the TopProductDTO class is:
其中 TopProductDTO 类是:
public class TopProductDTO {
public TopProductDTO() {}
private String text;
private Integer counter;
// Getters and Setters are omited
}
But when I execute the code
但是当我执行代码时
List<TopProductDTO> topProducts = productRepository.findTopProducts();
It returns a
它返回一个
List<Object[]> insted a List<TopProductDTO>
As like each column is a index of the Object Array in the list... Wasn't it supposed to Spring Data binds the 'text' and 'counter' columns from query with the fields in TopProductDTO?
就像每个列都是列表中对象数组的索引一样...... Spring Data 不是应该将查询中的“文本”和“计数器”列与 TopProductDTO 中的字段绑定吗?
As result I got a this error in my Thymeleaf Template:
结果,我的 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?
I'm using Spring Boot 1.3.3 and Postgres 9.2
我使用的是 Spring Boot 1.3.3 和 Postgres 9.2
回答by josivan
Try to use the constructor of your DTO.
尝试使用 DTO 的构造函数。
Declare a new constructor
声明一个新的构造函数
public TopProductDTO(String text, Integer count) {
this.text = text;
this.count = count;
}
In your query use the new Constructor
在您的查询中使用新的构造函数
@Query("SELECT new TopProductDTO(p.textToSearch, count(id))FROM Product p GROUP BY text_to_search ORDER BY counter DESC")
List<TopProductDTO> findTopProducts();
}
Use the fully qualified name of your class.
使用您的类的完全限定名称。