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

Spring Boot Query by Example传入参数查询不生效问题求助

问题原因

你的代码里searchByRegistration方法的registration参数没有绑定URL路径中的变量,导致Spring无法正确注入传入的参数,最终airplane.setRegistration(registration)设置的是null值。而Query by Example(QBE)的默认行为是忽略所有null属性,所以生成的SQL不会包含WHERE条件。

解决方案

给方法参数加上@PathVariable注解,让Spring将URL路径中{registration}对应的值注入到参数中:

// 修正后的Controller方法
@GetMapping("/nnumber/{registration}")
public List<Airplane> searchByRegistration(@PathVariable String registration) {
    Airplane airplane = new Airplane();
    airplane.setRegistration(registration);
    ExampleMatcher registrationMatcher = ExampleMatcher.matching()
            .withMatcher("registration", startsWith())
            .withIgnoreCase();
    Example<Airplane> example = Example.of(airplane, registrationMatcher);
    return airplaneRepository.findAll(example);
}

额外说明:

  • 这里把matchingAny()改成了matching(),因为你只需要匹配registration字段,matching()(默认匹配所有非null属性)更贴合需求,当然如果后续要加其他匹配字段,matchingAny()也可以用,但当前场景下matching()更合理。
  • 确保你的Airplane实体类中registration字段的getter/setter方法正确生成,QBE依赖这些方法来读取属性值。
验证效果

修改后,当你请求/nnumber/6时,Spring会正确将6注入到registration参数中,QBE会生成包含lower(a1_0.registration) like '6%' escape '\'的WHERE条件,从而查询出所有以6开头的飞机数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:42:48