I'm trying to do something which is easy as pie in PHP & Co: SELECT COUNT(x) as numItems, AVG(y) as average, ... FROM Z
In PHP I would get a simple array like [{ numItems: 0, average: 0 }] which I could use like this:
echo "Number of Items: " . $result[0]['numItems'];
Usually in JPQL you only query single objects or single columns and get Lists types, for example List<SomeEntity>
or List<Long>
. But what do you get, when querying multiple columns?
Its definition in JPQL is similar to SQL. You can provide one or more entity attributes to the ORDER BY clause and specify an ascending (ASC) or a descending (DESC) order. The following query selects all Author entities from the database in the ascending order of their lastName attributes.
The Jakarta Persistence Query Language (JPQL; formerly Java Persistence Query Language) is a platform-independent object-oriented query language defined as part of the Jakarta Persistence (JPA; formerly Java Persistence API) specification. JPQL is used to make queries against entities stored in a relational database.
The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.
JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.
You get an Object[]
(or a List<Object[]>
). From the section 4.8.1 Result Type of the SELECT Clause of the JPA 1.0 specification:
The result type of the SELECT clause is defined by the the result types of the select_expressions contained in it. When multiple select_expressions are used in the SELECT clause, the result of the query is of type
Object[]
, and the elements in this result correspond in order to the order of their specification in the SELECT clause and in type to the result types of each of the select_expressions.
If you want strong typing, you can use a constructor expression in the SELECT clause. From the section 4.8.2 Constructor Expressions in the SELECT Clause:
A constructor may be used in the SELECT list to return one or more Java instances. The specified class is not required to be an entity or to be mapped to the database. The constructor name must be fully qualified.
If an entity class name is specified in the SELECT NEW clause, the resulting entity instances are in the new state.
SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count) FROM Customer c JOIN c.orders o WHERE o.count > 100
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