How to do custom query with JPA + Hibernate

2

Hello,

I would like to know an elegant way to make a custom query using JPA .

Basically I want to run the query and return it to an object list, but usually it will be a query with N tables and only with the fields I will need.

I understand that I have to do POJO of the query return, but would I have some annotation or something else to help me make this link between the query return and the object? I do not want to have to pass line by line instantiating the object and column the column by filling in the properties of it.

    
asked by anonymous 15.01.2015 / 18:59

1 answer

2

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.

    
15.01.2015 / 19:20