Maintenance problem with JPA query

0

I have the following packages and classes.

When I'm going to do this JPA query, I need to pass all the class's fully qualified name (as it's in the example) because JPA can not find it if I just pass its name, no matter the class works.

Is there any way to solve this problem? Because I have to migrate some packages here in the project and will break about 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

}
    
asked by anonymous 25.10.2017 / 18:34

2 answers

0

You can use the getName() method of the VendaTotal class in your queries, so it is easier to refactor. String.format() or StringBuilder can 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();
    
27.10.2017 / 21:27
0

Try this:

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

With the result, you hit the total value.

    
27.10.2017 / 19:45