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
相关产品推荐
相关产品推荐

