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?
Query. Object getSingleResult() Execute a SELECT query that returns a single untyped result.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With