JPA中本机查询的字段值 [英] Field's value of native query in JPA
问题描述
如何获取本机查询(JPA)中某些字段的值?
How to get value of some fields in a native query (JPA)?
例如,我想获取客户表的名称和年龄:
For example I want to get name and age of customer table:
Query q = em.createNativeQuery("SELECT name,age FROM customer WHERE id=...");
注意:我不想将结果映射到实体.我只想获取该字段的值.
谢谢
推荐答案
具有多个选择表达式的本机查询返回Object[]
(或List<Object[]>
).根据规范:
A native query with multiple select expressions returns an Object[]
(or List<Object[]>
). From the specification:
3.6.1查询界面
...
3.6.1 Query Interface
...
Java结果的元素
带有SELECT子句的持久性查询
由多个选择组成
表达式的类型为Object[]
.如果
SELECT子句仅包含一个
选择表达式,元素
查询结果是对象类型.什么时候
使用本机SQL查询时,SQL
结果集映射(请参阅
3.6.6),确定有多少项(实体,标量值等)
回来.如果有多个项目
返回,查询的元素
结果的类型为Object[]
.如果只有一个
由于以下原因返回了单个项目
SQL结果集映射,或者
指定了结果类后,
查询结果的元素是
键入Object
.
The elements of the result of a Java
Persistence query whose SELECT clause
consists of more than one select
expression are of type Object[]
. If
the SELECT clause consists of only one
select expression, the elements of the
query result are of type Object. When
native SQL queries are used, the SQL
result set mapping (see section
3.6.6), determines how many items (entities, scalar values, etc.) are
returned. If multiple items are
returned, the elements of the query
result are of type Object[]
. If only a
single item is returned as a result of
the SQL result set mapping or if a
result class is specified, the
elements of the query result are of
type Object
.
因此,要在示例中获取姓名和年龄,您必须执行以下操作:
So, to get the name and age in your example, you'd have to do something like this:
Query q = em.createNativeQuery("SELECT name,age FROM customer WHERE id = ?1");
q.setParameter(1, customerId);
Object[] result = (Object[])q.getSingleResult();
String name = result[0];
int age = result[1];
参考文献
- JPA 1.0规范
- 第3.6.1节查询界面"
- 第3.6.6节"SQL查询"
- JPA 1.0 specification
- Section 3.6.1 "Query Interface"
- Section 3.6.6 "SQL Queries"
这篇关于JPA中本机查询的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
References