Hibernate ORDER BY ASC | DESC does not work by passing by parameter

1

Well, I have a problem with sorting a query, where I am passing the field name along with ASC or DESC as the query parameter, but hibernate is not finding himself, returning the query without the ordering. Would anyone have a solution to this problem?

Follow the code below:

String filtro = "nome DESC"; //ou "nome ASC"

Query query = manager
.createQuery("select t from ProdutosVO as t "+
"where t.codigoEmpresa = :paramCodigo ORDER BY :paramFiltro");
query.setParameter("paramCodigo", codigoEmpresa);
query.setParameter("paramFiltro", filtro);

Thank you in advance.

    
asked by anonymous 31.03.2016 / 22:43

2 answers

2

Well, I solved my problem by concatenating the filter directly in the query:

String filtro = "nome DESC"; //ou "nome ASC"

Query query = manager
.createQuery("select t from ProdutosVO as t "+
"where t.codigoEmpresa = :paramCodigo ORDER BY "+filtro);
query.setParameter("paramCodigo", codigoEmpresa);

However, the question is why hibernate does not accept order by as a parameter.

    
01.04.2016 / 14:07
4

It is not possible to use parameters for the Order By in this case you should create an "criteria" example:

Criteria c = manager.createCriteria(Classe.class);
c.createAlias("paramFiltro", "campo");
c.addOrder(Order.asc("paramFiltro.value"));
return c.list();
    
31.03.2016 / 23:48