Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

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.

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.

So how can I get the value of 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

Long rank = (Long) temp[0];
like image 793
Thang Pham Avatar asked Nov 14 '22 05:11

Thang Pham


1 Answers

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

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

like image 159
K Hein Avatar answered Dec 18 '22 21:12

K Hein