Maintenance problem with JPA query

Asked

Viewed 70 times

1

I have the following packages and classes.

When I’m going to do this JPA consultation, I need to go through the whole full Qualified name of the Class (as in the example) because JPA cannot find it if I pass only its name, no matter the class, it works.

Is there any way to solve this problem? Because I have to migrate some packages here in the project and will break some 20 queries and would have to go in each class and change manually.

br.com.projeto.dao.VendaDAO
br.com.projeto.model.Venda
br.com.projeto.model.VendaTotal

class VendaDao{

    public List<VendaTotal> getTotaisDeVentas(){
        String jpql = 
            "select new br.com.projeto.model.VendaTotal(sum v.valor) " +
            "from Venda v " +
            "group by v.data";
        return entityManager.createQuery(jpql, VentaTotal.class).getResultList();
    }

}

class Venda{
    private Double valor;
    private Date data;

    // getters e setters

}

class VendaTotal{
    private Double valor;

    public VentaTotal(Double valor){
        this.valor = valor;
    }

    // getters e setters

}
  • Are you sure you need to pass the full Qualified name? Ever tried without? Pq in the call of the method you speak which class: createQuery(jpql, VentaTotal.class)

  • @Igorventurelli yes.

2 answers

0

Try it that way:

String jpql = "select sum(v.valor) from Venda v group by v.data";

With the result, you set the total value.

0


You can use the method getName() class VendaTotal in your queries, so it is easier to refactor. The String.format() or the StringBuilder may also help you build this query.

String jpql = "select %s(sum(v.valor)) from Venda v group by v.data";
jpql = String.format(jpql,"new ".concat(VendaTotal.getClass().getName()));

Or

String jpql = "select new %s(sum(v.valor)) from Venda v group by v.data";
jpql = String.format(jpql, VendaTotal.getClass().getName());

With StringBuilder

StringBuilder builder = new StringBuilder();
builder.append("select ");
        .append("new ")
        .append(VendaTotal.getClass().getName())
        .append("(sum(v.valor)) ")
        .append("from Venda v group by v.data");
String jpql = builder.toString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.