I gave up trying to figure it out so I ask here :) my goal is to filter some data in database query by CriteriaBuilder. Each Client
has fields like howMuchOrders
and orderTotalValue
.
Here I try to check if my given atLeastAverageValue
is lower than averageTotalValueExpression
(calculated by dividing orderTotalValue
by howMuchOrders
). At very begining I need to check if my atLeastAverageValue
is not null. Otherwise I do not want to add predicate to list of executed predicates with query.
Everything works fine until root.get("orderCount")
gives zero (which is possible) and it throws org.springframework.dao.DataIntegrityViolationException
. I could catch and handle this exception, but it is not the way i like to do it. Firstly I'd like to check if value in root.get("orderCount")
is not null. If it is not - calculate and add prediacte to predicates list. Otherwise do nothing.
private void addMaxAveragePredicate(BigDecimal atLeastAverageValue, List<Predicate> predicates, CriteriaBuilder builder, Root<?> root) {
if (atLeastAverageValue!=null) {
Expression averageTotalValueExpression = builder.quot(root.get("orderCount"), root.get("orderTotalValue")).as(BigDecimal.class);
predicates.add(builder.lessThanOrEqualTo(averageTotalValueExpression, atLeastAverageValue));
}
}
Can anyone help?
Found the solution! I was not able to find out if the value is greater than 0 like in if
statement, but I imagined how would the sql query look. I just needed to check if orderCount > 0
and orderValue/order
in logical AND
:) looks like this:
predicates.add(builder.and(builder.greaterThan(root.get("orderCount"), 0),
builder.lessThanOrEqualTo(exQuot, attValue)));
I just needed some time :)