Spring_boot使用Example对象做条件查询
基本使用方法
@GetMapping("/subwayLines")
public ResponseListBase<SubwayLine> list(@RequestParam(required = false, defaultValue = "0") int page,
@RequestParam(required = false, defaultValue = "20") int size,
@RequestParam(required = false, defaultValue = "") String lineNo,
@RequestParam(required = false, defaultValue = "") String lineName) {
SubwayLine subwayLine = new SubwayLine();
ExampleMatcher em = ExampleMatcher.matching();
if(lineNo != null && !lineNo.equals("")) {
subwayLine.setLineNo(lineNo);
em = em.withMatcher("lineNo", GenericPropertyMatcher::startsWith);
}
if(lineName != null && !lineName.equals("")) {
subwayLine.setLineName(lineName);
em = em.withMatcher("lineName", GenericPropertyMatcher::startsWith);
}
Page<SubwayLine> subwayLinePage = repository.findAll(Example.of(subwayLine, em), PageRequest.of(page, size));
return new ResponseListBase<>(subwayLinePage);
}注意事项:官方用例写法:
ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("firstname", match -> match.endsWith()) .withMatcher("firstname", match -> match.startsWith());自己的写法:
ExampleMatcher em = ExampleMatcher.matching(); em = exampleMatcher.withMatcher("lineNo", ExampleMatcher.GenericPropertyMatcher::startsWith);其中重新付值是必须的,查看withMatcher代码会发现,返回一个新的对象,如果不做赋值,会导致没有配置模糊查询
第二个注意点是其中的
lineNo必须和对象的名称一致,如果line_no导致模糊查询不生效。