Spring Data return List< Object []> [英] Spring Data returning List<Object[]>

查看:111
本文介绍了Spring Data return 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类是:

where the TopProductDTO class is:

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中的字段?

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?

结果我在我的错误中遇到了这个错误Thymeleaf模板:

As result I got a this error in my Thymeleaf Template:

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

I'm using Spring Boot 1.3.3 and Postgres 9.2

推荐答案

尝试使用DTO的构造函数。

Try to use the constructor of your DTO.

声明一个新的构造函数

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.

这篇关于Spring Data return List&lt; Object []&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆