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

Posted

技术标签:

【中文标题】附加 QueryDSL 谓词或基于过滤器值构建谓词【英文标题】:Append QueryDSL Predicate or building predicate based on filter values 【发布时间】:2021-04-13 16:58:39 【问题描述】:

我是 Querydsl 的新手,我正在寻找一种基于过滤器附加/构建谓词的方法。您可以在示例中看到,如果过滤器中的某个字段没有值,则不应进入谓词。

如果这样的事情是不可能的,那么最好的方法是什么?

例如过滤器(GetPaintingRequest)包含这些字段(过滤器中有更多,但不重要):

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

    //.....getters and setters

所以在服务类中我想像这样过滤绘画

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);


【问题讨论】:

【参考方案1】:

我找到了解决办法!

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);

【讨论】:

以上是关于附加 QueryDSL 谓词或基于过滤器值构建谓词的主要内容,如果未能解决你的问题,请参考以下文章

为 oneTomany 基于关系的查询编写 queryDSL 谓词查询

如何使用 BooleanBuilder (QueryDSL) 为可选的 OnetoOne JPA/Hibernate 关系建模谓词?

带有 Querydsl 的 JPA 谓词

有没有办法通过 QueryDSL 中的谓词 API 急切地获取惰性关系?

如何基于谓词实现列表拆分器

lambda-基于谓词筛选值序列