java JPA:createNativeQuery.getSingleResult() 返回一个对象,如何获取该对象内一个属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4404373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:13:37  来源:igfitidea点击:

JPA: createNativeQuery.getSingleResult() return an object, how I can get the value of one attribute inside that object

javajpa

提问by Thang Pham

I have a query like this

我有这样的查询

SET @rownum := 0; 
SELECT rank, id, point FROM
      (
      SELECT @rownum := @rownum + 1 AS rank, id, point FROM user ORDER BY point DESC
      ) AS result
WHERE id = 0;

So I use EntityManager#createNativeQueryto execute this query.

所以我EntityManager#createNativeQuery用来执行这个查询。

Object temp = em.createNativeQuery(sql).getSingleResult(); //sql is the above SQL query

So now object temphold information about rank, id, and point. Note that rankis not an attribute inside my Entity, rankis calculated when the query execute --> cant cast this object to my Entity.

所以现在反对temp有关保全的信息rankidpoint。请注意,这rank不是我的实体内的属性,rank是在查询执行时计算的 --> 无法将此对象转换为我的实体。

So how can I get the value of rank?

那么我怎样才能获得 的价值rank呢?

EDIT
Here is the answer to what I am looking for. So instead of this

编辑
这是我正在寻找的答案。所以而不是这个

Object temp = em.createNativeQuery(sql).getSingleResult();

Do this

做这个

Object[] temp = (Object [])em.createNativeQuery(sql).getSingleResult();

Since I want to know the value of rank, then I would do this

既然我想知道 的价值rank,那么我会这样做

Long rank = (Long) temp[0];

回答by K Hein

createNativeQuery method creates a Query instance. You have to invoke getResultList() or getSingleResult() on the Query object to actually execute the query.

createNativeQuery 方法创建一个 Query 实例。您必须对 Query 对象调用 getResultList() 或 getSingleResult() 才能实际执行查询。

http://download.oracle.com/javaee/5/api/javax/persistence/Query.html

http://download.oracle.com/javaee/5/api/javax/persistence/Query.html