Suppose the following entity:
Entity {
Integer id;
Boolean imported;
Integer status;
}
The task is: When selecting entities those with imported = true
AND status != 1
should go to the bottom of search result. It is also necessary to use CriteriaBuilder
.
I decided to compute the value which will indicate them to be pulled down by the following expression: imported = true AND status != 1
If writing direct SQL it works as intended having a look:
SELECT .. FROM .. ORDER BY (imported = true AND status != 1) ASC
However I cannot transcode it in context of CriteriaBuilder
I tried to do it like this:
Predicate eqTruePredicate = cb.equal(root.get(Entity_.imported), true);
Predicate neqStatusPredicate = cb.notEqual(root.get(Entity_.status)), 1);
Predicate andExp = cb.and(eqTruePredicate, neqStatusPredicate);
order.add(0, new OrderImpl(cb.isTrue(andExp)));
The generated query is the following:
order by ( generatedAlias0.imported=:param2 ) and ( generatedAlias0.status<>:param3 ) asc
But when execute the exception is thrown saying: "unexpected AST node" pointing at token and
Is there a way to perform ordering by computed value using CriteriaBuilder
and what would be necessary to be done?
Addition: Hibernate ORM version: 4.3.5
I managed to do it using CASE
statement:
Expression<Integer> caseExp = cb.<Integer>selectCase()
.when(
cb.and(
cb.equal(root.get(Entity_.imported), true),
cb.notEqual(root.get(Entity_.status), 1)
),
1
)
.otherwise(0);
order.add(0, cb.asc(caseExp));
This results into an ORDER BY
statement like this:
order by case when ( entity.imported=true ) and ( entity.status<>1 ) then 1 else 0 end asc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.