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
JPA: createNativeQuery.getSingleResult() return an object, how I can get the value of one attribute inside that object
提问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#createNativeQuery
to execute this query.
所以我EntityManager#createNativeQuery
用来执行这个查询。
Object temp = em.createNativeQuery(sql).getSingleResult(); //sql is the above SQL query
So now object temp
hold information about rank
, id
, and point
. Note that rank
is not an attribute inside my Entity, rank
is calculated when the query execute --> cant cast this object to my Entity.
所以现在反对temp
有关保全的信息rank
,id
和point
。请注意,这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