简体   繁体   English

使用 querydsl 按 null 搜索

[英]Search by null with querydsl

I have a controller method for searching like so我有一个控制器方法可以像这样搜索

@RequestMapping(method = RequestMethod.GET)
public Page<MyEntity> find(@QuerydslPredicate(root = MyEntity.class)
                                     Predicate predicate,
                         Pageable pageable) {

    return this.myEntityRepository.findAll(predicate, pageable);
}

It works great.它工作得很好。 I can issue a GET request with various query string parameters, and it filters accordingly, but now I want to search by null.我可以使用各种查询字符串参数发出GET请求,并相应地进行过滤,但现在我想按 null 进行搜索。 I tried doing something like /myentity?myParam1=& , but the predicate argument is always null .我尝试做类似/myentity?myParam1=&事情,但predicate参数始终为null

How can I search where specific fields are null?如何搜索特定字段为空的位置?

There is no way to search an entity by null parameters like myParam1=null , because it throws a NullPointerException.没有办法通过像myParam1=null这样的空参数来搜索实体,因为它会抛出一个 NullPointerException。 I had the same problem and this is the only way I could make it work.我遇到了同样的问题,这是我让它工作的唯一方法。


@RequestMapping(method = RequestMethod.GET)
public Page find(@QuerydslPredicate(root = MyEntity.class) Predicate predicate, Pageable pageable, @RequestParam MultiValueMap parameters) {

    Page entities = myEntityRepository.findAll(predicate, pageable);
    if(parameters.get("myParam1") != null && 
            parameters.get("myParam1").get(0) != null &&
            parameters.get("myParam1").get(0).isEmpty()) {

        QEntity entity = QEntity.entity;
        BooleanExpression myParam1IsNull = entity.in(entities.getContent()).and(entities.myParam1.isNull());
        entities = myEntityRepository.findAll(myParam1IsNull, pageable);
    }

    return entities;
}

It performs two queries to the database, but it solves the problem.它对数据库执行两次查询,但它解决了问题。 I hope this helps you.我希望这可以帮助你。

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

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