2016-03-01 89 views
2

我有这个资源库:春数据返回列表<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 1.3.3引导和Postgres 9.2

回答

8

尝试使用您的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(); 
} 

使用你的类的全名。

+0

在[hibernate文档](https://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/queryhql.html)中,您也可以看到一些很好的示例。 – josivan

+0

当我这样做时,编译失败,错误“验证失败,查询...”。没有其他堆栈跟踪有意义。任何想法为什么会这样呢? –

+0

什么是完整验证错误消息?请确保您在前面提到的类名称包含前缀 – 2017-08-05 04:17:28