12

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?

Jan Algermissen
  • 4,930
  • 4
  • 26
  • 39

1 Answers1

17

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.

eckes
  • 10,103
  • 1
  • 59
  • 71
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Doh, thanks. Did not understood that was possible from the docs: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createNativeQuery(java.lang.String) [Note that I had to use an object type and use its intValue() to make your example work.] – Jan Algermissen Dec 01 '11 at 14:23
  • I updated the solution to use `(Number)...longValue()` which is a super type of `BigInteger`, I am not sure if there is any DB/driver which does not return a subtype of `Number` for this case but the `(long)` cast in the origiinal answer does "never" work for me. (I also wonder if you could specify `Number.class` as a type mapping just to be sure (Double.class seems not to work: http://stackoverflow.com/questions/8959771/jpql-native-query-using-sum-and-count) – eckes Jan 12 '16 at 15:12