简体   繁体   English

QueryDSL多参数搜索,同时在值为null时构建查询跳过谓词

[英]QueryDSL multiparameter search, while building the query skip predicate when value is null

I'm working on a Spring Boot web application with QueryDSL JPA. 我正在使用QueryDSL JPA开发Spring Boot Web应用程序。 I have a REST api where i get form input from users. 我有一个REST api,我从用户那里获得表单输入。 I have to perform a multi parameter search. 我必须执行多参数搜索。 If a value of the users inpu is null (which is ok, cause not all fields are requiered), my query builder should skip this value while querying the database. 如果用户inpu的值为null(可以,因为并非所有字段都被取消),我的查询构建器应该在查询数据库时跳过此值。

On my QueryDSL part, i get an Object, for example "Solution", it may look like this: 在我的QueryDSL部分,我得到一个Object,例如“Solution”,它可能如下所示:

ticketNumber: 4261 (Integer) ticketNumber:4261(整数)
errorFlag: false (Boolean) errorFlag:false(布尔值)
statusOCIA: null (string) statusOCIA:null(字符串)
description: "Erorr while clicking an image" (String) description:“单击图像时出现错误”(String)

I tried to build a query dynamically with PathBuilder and BooleanBuilder from QueryDSL: 我尝试使用来自QueryDSL的PathBuilder和BooleanBuilder动态构建查询:

    public List<Solution> findSolutionBySolutionQuerydsl(Solution searchSolution) {


    QSolution solution = QSolution.solution;
    JPAQuery<?> query = new JPAQuery<Void>(em);


    BooleanBuilder builder = new BooleanBuilder();
    PathBuilder<QSolution> QentityPath = new PathBuilder<QSolution>(QSolution.class, "solution");
    PathBuilder<Solution> entityPath = new PathBuilder<Solution>(Solution.class, "serachSolution");

    Field[] fields = searchSolution.getClass().getDeclaredFields();


    for (Field attr : fields) {

        if (searchSolution."here it should perform searchSolution.getTicketNumber or searchSolution.getDiscription depending on what attr.getName is"  != null) {
            builder.or(QentityPath.get(attr.getName()).eq(entityPath.get(attr.getName())));

        }
    }

    List<Solution> s1 = query.select(solution)
            .from(solution)
            .where(builder)
            .fetch();

    System.out.println(("query: " + s1));

    return s1;

}

I want that it will work like this: If attr.getName is "description", it should perform searchSolution.getDescription. 我想它会像这样工作:如果attr.getName是“description”,它应该执行searchSolution.getDescription。

I tried some stuff with a HashMap or ArrayList but failed due to the different data types in my Object. 我尝试了一些HashMap或ArrayList的东西,但由于我的Object中的数据类型不同而失败了。

I hope someone can help me. 我希望有一个人可以帮助我。

Try to put this check in the if condition 尝试将此检查置于if条件中

entityPath.get(attr.getName()) != null

to make it 做到这一点

if (entityPath.get(attr.getName()) != null) {

    builder.or(QentityPath.get(attr.getName()).eq(entityPath.get(attr.getName())));
}

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

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