How to Order List (Hibernate)

1

How can I sort 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();
}

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 you have any way to do an "Order By" or something else?

    
asked by anonymous 02.05.2017 / 16:28

2 answers

3

You can also apply sorting through the "OrderBy" annotation directly in the entity attribute.

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

Workaround is to apply sorting directly on the return collection with Comparable and Comparator.

    
03.05.2017 / 12:21
1

In JPQL, simply use ORDER BY followed by the name of the variable in your entity. Here is an example by ordering 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, this is an ascending sort. If you want to downgrade, just add DESC to the end:

+ " ORDER BY situacao DESC ";
    
02.05.2017 / 16:37