2016-03-01 62 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