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

Asked

Viewed 419 times

1

Well, I’m having a problem ordering a query, where I’m passing the name of the field along with ASC or DESC as parameter for the query, however Hibernate is not finding itself, returning the query without sorting. Someone would have a solution for this problem?

Follow the code:

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);

Thanks in advance.

2 answers

4

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

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

2


Well, I solved my problem as follows, concatenating the filter directly into 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, it is doubtful why Hibernate does not accept order by as parameter.

Browser other questions tagged

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