Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Native query get a Single Object

How can i get a single object by using JPA Native query. I did some researches but all give an answer is use "getSingleResult", however it didn't return what i want to get. For example, what should i do if i want to get a count of table in my database and fetch it into a Integer.

This code below shows how i get this by using Sessison hibernate:

int check = Integer.parseInt((String) sessionF.createSQLQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").uniqueResult()); 

And what i hope to be fine in JPA:

int check = Integer.parseInt((String) getEntityManager().createNativeQuery("select to_char(count(*)) as count from user_tables where table_name upper('TEST')").getSingleResult()); 

Obviously, the code doesn't return what i want. Therefore, please help me to cope with this problem. Thank you !

like image 740
minh Avatar asked Mar 28 '16 03:03

minh


People also ask

Which method is used for getting single object as result out of query?

The getResultIterator method runs a SELECT query and returns the query results using an Iterator where each result is either an Object for a single-valued query, or an Object array for a multiple-valued query.

Which is faster JPQL or native query?

In some cases it can happen Hibernate/JPA does not generate the most efficient statements, so then native SQL can be faster - but with native SQL your application loses the portability from one database to another, so normally is better to tune the Hibernate/JPA Query mapping and the HQL statement to generate more ...

What is the difference between native query and JPA query?

In JPA, you can create a query using entityManager. createQuery() . You can look into API for more detail. Native query refers to actual sql queries (referring to actual database objects).


3 Answers

With JPA you need to do like following

int num = ((Number)this.entityManager.createNativeQuery("select count(*) from your_table_name")
                .getSingleResult()).intValue();

edited :

 String name = this.entityManager.createNativeQuery("select t.name from your_table_name t limit 1").getSingleResult().toString();

you will got count with num object

Hope its will help to you.

like image 161
Ravi Kavaiya Avatar answered Oct 11 '22 22:10

Ravi Kavaiya


In case of native query with multiple select expressions returns an Object[] (or List<Object[]>).

you can use below example code as per your requirement .

Query q = em.createNativeQuery("SELECT id,name FROM user WHERE id = ?1");
q.setParameter(1, userId);
Object[] result = (Object[])q.getSingleResult();
String id= result[0];
int name = result[1];

You might need to typecast the result Array values.

like image 24
Sai prateek Avatar answered Oct 11 '22 22:10

Sai prateek


This may help someone. To get a single object you can choose either of the below:

Method 1:

Query theQuery = entityManager.createNativeQuery("SELECT * from yourTable where yourTableId = (Select MAX(yourTableId) from yourTable where empId = ?1 and instId = ?2 GROUP BY empId,instId)",YourTableEntity.class);
theQuery.setParameter(1, empId);
theQuery.setParameter(2, instId);
System.out.println(theQuery.getSingleResult()); 

Method 2:

Query theQuery = entityManager.createNativeQuery("SELECT * from yourTable where empId = ?1 and instId = ?2 order by yourTableId DESC");   
theQuery.setParameter(1, empId);
theQuery.setParameter(2, instId);
theQuery.setMaxResults(1); //Use if it makes good impact in complexity
System.out.println(theQuery.getResultList().get(0));

NOTE: For simplicity sake I just printed it. You may need to typecast. Check if the time taken by method 1 or method 2 works better for you.

like image 24
Keegs Avatar answered Oct 11 '22 22:10

Keegs