How to Sort List (Hibernate)

Asked

Viewed 1,024 times

1

How can I order a List with java and Hibernate?

I have an abstract class with this method

public List<T> listarContas(String where) {
    String consulta = "FROM " + entityClass.getSimpleName()+ " where "+ where;
    Query query = getEntityManager().createQuery(consulta);
    return query.getResultList();
}

and I have the controller with this method that calls the list

public List<Usuario> getListaUsuariosAtivados(){
   listaUsuarios = usuarioFacade.listarContas("(situacao) = 'Ativo'");
   return listaUsuarios;
}

I’m using Java, Hibernate, Mysql, and Primefaces.

Would have some way to make one "Order By" or something else?

2 answers

3


You can also apply sorting via the "Orderby" annotation directly to the entity attribute.

    @Entity 
    public class Escola{
       ...
       @ManyToMany
       @OrderBy("ultimoNome ASC")
       public Set<Estudante> getEstudantes() {...};
       ...
    }

Alternative solution is to apply sorting directly in the return collection with Comparable and Comparator.

3

In JPQL, simply use ORDER BY followed by the variable name in your entity. Follow an example by situacao:

public List<T> listarContas(String where) {
    String consulta = "FROM " + entityClass.getSimpleName()+ " where "+ where
    + " ORDER BY situacao ";
    Query query = getEntityManager().createQuery(consulta);
    return query.getResultList();
}

By default, it is an ascending ordering. If you want to make descending, just add DESC at the end:

+ " ORDER BY situacao DESC ";
  • 1

    Thank you very much, it worked out that’s what I was looking for :D

Browser other questions tagged

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