gpt4 book ai didi

java - 返回 List 的 Spring Data

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:31 27 4
gpt4 key购买 nike

我有这个存储库:

@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 不应该将查询中的“文本”和“计数器”列与 TopProductDTO 中的字段绑定(bind)吗?

结果我的 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

最佳答案

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

使用类的完全限定名称。

关于java - 返回 List<Object[]> 的 Spring Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714245/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com