gpt4 book ai didi

java - JPQL:查询多列时,什么样的对象包含结果列表?

转载 作者:搜寻专家 更新时间:2023-10-31 20:07:16 26 4
gpt4 key购买 nike

我正在尝试做一些在 PHP & Co 中非常简单的事情:选择 COUNT(x) 作为 numItems,AVG(y) 作为平均值,... FROM Z

在 PHP 中,我会得到一个像 [{ numItems: 0, average: 0 }] 这样的简单数组,我可以这样使用它:

echo "Number of Items: " . $result[0]['numItems'];

通常在 JPQL 中您只查询单个对象或单个列并获取列表类型,例如 List<SomeEntity>List<Long> .但是,当查询多列时,您会得到什么?

最佳答案

你得到一个 Object[] (或 List<Object[]> )。来自 JPA 1.0 规范的 4.8.1 SELECT 子句的结果类型部分:

The result type of the SELECT clause is defined by the the result types of the select_expressions contained in it. When multiple select_expressions are used in the SELECT clause, the result of the query is of type Object[], and the elements in this result correspond in order to the order of their specification in the SELECT clause and in type to the result types of each of the select_expressions.

如果你想要强类型,你可以在 SELECT 子句中使用构造函数表达式。摘自 4.8.2 SELECT 子句中的构造函数表达式:

A constructor may be used in the SELECT list to return one or more Java instances. The specified class is not required to be an entity or to be mapped to the database. The constructor name must be fully qualified.

If an entity class name is specified in the SELECT NEW clause, the resulting entity instances are in the new state.

SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
FROM Customer c JOIN c.orders o
WHERE o.count > 100

关于java - JPQL:查询多列时,什么样的对象包含结果列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2936685/

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