-
Couldn't load subscription status.
- Fork 8
Sorting data
Sorting values can be done by using the orderBy() method and subsequently calling the desc(...) or asc(...) methods. These methods can be chained.
Person person = query.from(Person.class);
query.selectValue(person.getName());
query.selectValue(person.getAge());
query.orderBy().desc(person.getName()).
asc(person.getAge());
hqlQuery.getHql() would yield =>
"select hobj1.name, hobj1.age from Person hobj1 order by hobj1.name desc, hobj1.age"It is also possible to order by a projection alias. This can be useful when there is no prefixed ordering and utilizing paging when querying. Since the mapping of which data is selected into which field of the result type is already done, it is easy to simply set the aliases to order by.
Person person = query.from(Person.class);
PersonDto dto = query.select(PersonDto.class);
dto.setThePersonsName(person.getName()); // binds the name to the 'thePersonName' property
query.orderBy().by(new OrderByProjection(query, "thePersonsName", true)); // sort by result field
hqlQuery.getHql() would yield =>
"select hobj1.name as thePersonsName from Person hobj1 order by hobj1.name desc"This feature is mainly useful when there is dynamic sorting and the outside code, which should not have knowledge about how the query is constructed, needs to define the sorting.
In addition to this programmatic approach to add a projection alias to order by it is also possible to use the getter of the dto. This way it is possible to think of the sorting separate from the selecting process. So when the data selected into the dto changes, the sorting won't have to be adjusted too.
Person person = query.from(Person.class);
PersonDto dto = query.select(PersonDto.class);
dto.setThePersonsName(person.getName());
query.orderBy().desc(dto.getThePersonsName());
hqlQuery.getHql() would yield =>
"select hobj1.name as thePersonsName from Person hobj1 order by hobj1.name desc"This concludes the basic introduction, check out the additional topics on the homepage for more information.