You can use the NEW keyword of JPQL in the query, specifying a class. For each row returned, an instance of this class is created. And then you can pass the type of your data structure as a parameter when you request the EntityManager query.
This data structure (or "class") needs to declare a constructor that receives field values in the order in which they are selected in the query.
So, considering this data structure:
package org.learning;
class ContaAtrasada {
final int idConta;
final double valor;
final int diasEmAtraso;
ContaAtrasada(int idConta, double valor, int diasEmAtraso) {
this.idConta = idConta;
this.valor = valor;
this.diasEmAtraso = diasEmAtraso;
}
}
The method that performs the query would look something like this:
public List<ContaAtrasada> findContasAtrasadas() {
return em.createQuery("select NEW org.learning.ContaAtrasada(c.idConta, c.valor, " +
"today - c.dataVencimento as diasEmAtraso) " +
"from Conta c where c.dataVencimento < today", ContaAtrasada.class)
.getResultList();
}
I have explicit the namespace ( package ) of the class because it is very important to inform you in your JPQL query, since the query can be executed in another context where your class will not be directly accessible.