简体   繁体   中英

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. I have a REST api where i get form input from users. 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.

On my QueryDSL part, i get an Object, for example "Solution", it may look like this:

ticketNumber: 4261 (Integer)
errorFlag: false (Boolean)
statusOCIA: null (string)
description: "Erorr while clicking an image" (String)

I tried to build a query dynamically with PathBuilder and BooleanBuilder from QueryDSL:

    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.

I tried some stuff with a HashMap or ArrayList but failed due to the different data types in my Object.

I hope someone can help me.

Try to put this check in the if condition

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

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