Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving single value using JPA?

Tags:

jpa

Is there any support by JPA to map single values to scalar data types? For example, to map NUM in the following query

SELECT COUNT(*) AS NUM FROM EMPLOYEES

to some variable

int numerOfEmployees

or do I have to use JDBC for such use cases?

like image 371
Jan Algermissen Avatar asked Dec 01 '11 14:12

Jan Algermissen


People also ask

How can I get single result in JPA?

Query. Object getSingleResult() Execute a SELECT query that returns a single untyped result.

What is the use of @query in JPA?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.

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.


1 Answers

Yes, you can return scalar types from JPQL queries

long num = ((Number)em.createQuery("select count(e) from Employee e")
                    .getSingleResult()).longValue();

as well as from native SQL queries:

long num = ((Number)em.createNativeQuery("select count(*) from Employees")
                    .getSingleResult()).longValue();

Note that in some cases result type may depend on the database, i.e. it can be something like BigDecimal.

like image 162
axtavt Avatar answered Sep 24 '22 18:09

axtavt