2
I have a indexed search with the Hibernate Search but I can’t get Hibernate Search order the search result in the order of a given column, as for example the name column.
But there is a peculiarity. When the search is done using some term, the result is then ordered perfectly alphabetically. However, if I don’t put any term in the search (I want to return all results), then Hibernate Search no longer orders anything.
See the codes related to the two searches:
Using a filter (works)
Below is my method that searches filtering through a term. This search works perfectly and neatly by name (alphabetically).
public List<Colaborador> filtrar(String termo) throws DAOException {
try {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
Query query = qb.keyword().onFields("nome", "email", "usuario").matching(termo).createQuery();
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query);
// Ordenação ocorre corretamente aqui!
Sort sortField = new Sort(new SortField("nome", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
catch (Exception e) {
logger.error("Erro ao filtrar colaboradores com termo: " + termo, e);
throw new DAOException(e);
}
}
Bringing all records (does not work ordering)
Below is a method very similar to what I posted above, however the method below just does not correctly sort the records that are returned by Hibernate Search. Note that it is the same entity (Colaborador.class
) and yet the order by name doesn’t work properly.
public List<Colaborador> listarColaboradores() throws DAOException {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(qb.all().createQuery());
// A mágica deveria ser feita aqui!
Sort sortField = new Sort(new SortField("nome", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
Has anyone been there? You know what might be happening?