简体   繁体   中英

How to check null and apply filter in JPA Querydsl?

I have a scenario like below and i am using JPA Query DSL:

List<Student> allStudents(String inputDob){
     List<Student> resultList = jpaQuery.from(student)
                    .where(student.dob.eq(inputDob) //how to skip this condition in case inputdob is null
                    .and(student.age.eq(25)))    
                    .fetch(); 
}
//My question is suppose : inputDob is null then how to skip the where clause if parameter is comming as null?

An if/else statement might work for you.

List<Student> allStudents(String inputDob){
    List<Student> resultList = null;
    if (inputDob == null || inputDob.isEmpty()) {
         resultList = jpaQuery.from(student)
                .where(student.age.eq(25))
                .fetch();
    } else {
        resultList = jpaQuery.from(student)
                .where(student.dob.eq(inputDob)
                        .and(student.age.eq(25)))
                .fetch();
    }
}

You initialize the resultList before the if/else statement, so you can avoid compilation errors later. Then you run the appropriate query, depending on the input.

Please let me know if this was helpful for your case.

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