简体   繁体   English

Append QueryDSL 谓词或基于过滤器值构建谓词

[英]Append QueryDSL Predicate or building predicate based on filter values

I'm new to Querydsl and Im looking for a way to append/build predicate based on filters.我是 Querydsl 的新手,我正在寻找一种基于过滤器附加/构建谓词的方法。 You can see in the example that if one of the fields in the filter doesn't have value it shouldn't go in predicate.您可以在示例中看到,如果过滤器中的某个字段没有值,则它不应该在谓词中使用 go。

If something like this is not possible, what is the best approach then?如果这样的事情是不可能的,那么最好的方法是什么?

For example filter (GetPaintingRequest) contains these fields (there are more in the filter, but not important):例如过滤器(GetPaintingRequest)包含这些字段(过滤器中有更多,但不重要):

public class GetPaintingsRequest {
    private String author;
    private Integer style;
    private String paintingName;

    //.....getters and setters
}

So in a service class I want to filter painting like this所以在服务 class 我想像这样过滤绘画

public List<Painting> getFilteredPaintings(GetPaintingsRequest request) {
        
        QPainting painting = QPainting.painting;
        
        //predicate for all paintings that are not deleted and not sold
        Predicate query = painting.deleted.isFalse().and(painting.isSold.isFalse());
        
        if (!request.getAuthor().equals("")) {
            //append to existing predicate name of the author
            query.and.painting.autor.eq(request.getAuthor()); //obviously not working - just as an example what I want
            
        }

        if (!request.getPaintingName().equals("")) {
            //append to existing predicate painting name
            query.and.painting.paintingName.eq(request.getPaintingName()); //obviously not working - just as an example what I want
        }
        
        var paintingList = paintingRepository.findAll(query);

}

I've found a solution!我找到了解决方案!

QPainting painting = QPainting.painting;
        
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        
        booleanBuilder.and(painting.deleted.isFalse().and(painting.isSold.isFalse()));      
        

        if (!request.getAuthor().equals("")) {
            booleanBuilder.and(painting.author.eq(request.getAuthor()));

        }

        if (!request.getPaintingName().equals("")) {
            booleanBuilder.and(painting.paintingName.eq(request.getPaintingName()));
        }
        
        
        
        Predicate predicate = booleanBuilder;
        var paintingList = paintingRepository.findAll(predicate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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