Retrieving single value using JPA?

2020-03-11 02:58发布

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?

标签: jpa
1条回答
够拽才男人
2楼-- · 2020-03-11 03:41

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.

查看更多
登录 后发表回答