Spring Data返回List<Object[]>

5

我有这个代码库:

@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

1个回答

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

使用您的类的完全限定名称。


hibernate文档中,你也可以看到一些很好的例子。 - josivan
当我这样做时,编译失败并显示错误消息“验证查询失败...”。没有其他有意义的堆栈跟踪。你有任何想法为什么会发生这种情况吗? - Nikhil Sahu
1
完整的验证错误信息是什么?请确保按照之前提到的方式为您的类包名称添加前缀。 - user2964500
这个问题让我无法正常思考。解决方案非常有效,谢谢你。 - Vishal
1
在Repository层使用DTO是否可行?难道不应该在Service层将object[]转换为DTO吗? - Mihir Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接