gpt4 book ai didi

orm - JPA中原生查询的字段值

转载 作者:行者123 更新时间:2023-12-03 21:34:31 25 4
gpt4 key购买 nike

如何在 native 查询(JPA)中获取某些字段的值?

例如,我想获取客户表的名称和年龄:

Query q = em.createNativeQuery("SELECT name,age FROM customer WHERE id=...");

注意:我不想将结果映射到实体。我只想获取该字段的值。

谢谢

最佳答案

具有多个选择表达式的 native 查询返回 Object[] (或 List<Object[]> )。从规范:

3.6.1 Query Interface

...

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.



因此,要获取示例中的姓名和年龄,您必须执行以下操作:
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节“查询接口(interface)”
  • 第 3.6.6 节“SQL 查询”
  • 关于orm - JPA中原生查询的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3599450/

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