简体   繁体   中英

How to filter by calculated field using Querydsl Predicate (BooleanExpression) with Spring Data?

There're two numeric columns in database like actual and plan.

I can add third column like difference and write WHERE part of query filtering by this column.

But instead having additional column in database, I want to calculate it in Predicate.

Something like (qProduct.actualPrice - qProduct.planPrice).gt(20L)

Entity:

public class Product {
    private String type;
    private Long actualPrice;
    private Long planPrice;
}

Predicate:

QProduct qProduct = QProduct.product;
BooleanExpression predicate = qProduct.type.eq("pizza")
            .and((qProduct.actualPrice - qProduct.planPrice).gt(20L));

Page<Product> productPage = productRepository.findAll(predicate, pageable);

Thx

You can use the subtract method of NumberExpression class

QProduct qProduct = QProduct.product;
BooleanExpression predicate = qProduct.type.eq("pizza")
          .and((qProduct.actualPrice.subtract(qProduct.planPrice)).gt(20L));

Page<Product> productPage = productRepository.findAll(predicate, pageable);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM