【问题标题】:Spring Data returning List<Object[]>Spring Data 返回 List<Object[]>
【发布时间】:2016-06-13 08:37:37
【问题描述】:

我有这个仓库:

@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 中的字段绑定吗?

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

【问题讨论】:

    标签: java spring postgresql spring-boot spring-data


    【解决方案1】:

    尝试使用 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 documentation 你也可以看到一些很好的例子。
    • 当我这样做时,编译失败并出现错误Validation failed for query...。没有其他有意义的堆栈跟踪。任何想法为什么会发生这种情况?
    • 什么是完整的验证错误信息?如前所述,确保为类包名称添加前缀
    • 这个问题让我无法思考。该解决方案就像一个魅力,谢谢。
    • 在 Repository 层使用 DTO 是否可取? object[]不应该在服务层转换为DTO吗?
    猜你喜欢
    • 2022-01-14
    • 2015-09-09
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多