You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Mongo JPA的@Query注解中编写动态查询

Spring Mongo @Query实现非空字段筛选及Criteria Builder问题

我想通过Spring Mongo的@Query注解编写查询语句,实现仅根据前端传来的非空字段筛选数据,但目前尝试的写法都返回了所有记录:

第一次尝试的代码:

@Query("{ { $or: [ { $where: '?0 == null' }, { name: '?0' } ] }" +
        " { $or: [ { $where: '?1 == null' }, { age: '?1' } ] }" +
        " { $or: [ { $where: '?2 == null' }, { batch: '?2' } ] }" +
        " { $or: [ { $where: '?3 == null' }, { $or: [{startDate: '?3'}, {endDate: '?3'}] } ] } }")

编辑补充:后来我把$or嵌套在$and中,结果还是返回所有记录:

@Query("{$and:{"
        + "   { $or: [ { $where: '?0 == null' }, { name: '?0' } ] },"
        + "   { $or: [ { $where: '?1 == null' }, { age: '?1' } ] },"
        + "   { $or: [ { $where: '?2 == null' }, { batch: '?2' } ] },"
        + "}}")

编辑补充:之后我尝试用Criteria Builder来实现,但现在提示找不到find()方法(代码中query对象调用find()时标红报错)。

内容的提问来源于stack exchange,提问作者confused_geek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:05:18