在后端开发中,要实现多字段模糊查询和外键的投影映射,必须重新写查询接口,才能实现模糊查询和外键映射兼得。
如下所示是多字段模糊查询的抽象类,接口只要继承就可以。
/**
* 多字段模糊化搜索抽象类
*
* @param <T> 需要模糊化搜索的实体类
*/
public abstract class FuzzySearchController<T> {
// 根据实体类声明其数据库操作接口
@Autowired
protected JpaRepository<T, Long> repository;
// 匹配规则
protected final ExampleMatcher defaultExampleMatcher =
ExampleMatcher.matching().
withIgnoreCase(). // 忽略大小写
withIgnorePaths("id"). // 忽略 id(因为有 id 会变成单个查询)
withIgnoreNullValues(). // 忽略 null 值
withIgnorePaths("learnNumbers").
withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING); // 字符串匹配规则为包含
@GetMapping("/fuzzy")
public ResponseEntity<PagedResources> fuzzySearch(T x, Pageable pageable) {
Page<T> data = repository.findAll(Example.of(x, defaultExampleMatcher),pageable);
PagedResources.PageMetadata pageMetadata =
new PagedResources.PageMetadata(
data.getSize(), // 每页大小
data.getNumber(), // 当前页数(从 0 开始)
data.getTotalElements(), // 总记录条数
data.getTotalPages() // 总页数
);
return ResponseEntity.ok(wrap(data, pageMetadata));
}
}
要两个都实现必须添加投影配置类,如下所示:
@Configuration
public class ProjectionConfiguration {
@Bean
public SpelAwareProxyProjectionFactory projectionFactory() {
return new SpelAwareProxyProjectionFactory();
}
}
然后重写接口:
@GetMapping("/fuzzy-projection")
public ResponseEntity<PagedResources> fuzzyCourseListsesProjection(CourseLists courseLists,Pageable pageable){
Page<CourseLists> data=repository.findAll(Example.of(courseLists,defaultExampleMatcher),pageable);
Page<CourseListInline> projectionData=data.map(
courseLists1 -> projectionFactory.createProjection(CourseListInline.class,courseLists1));
PagedResources.PageMetadata pageMetadata =
new PagedResources.PageMetadata(
data.getSize(),
data.getNumber(),
data.getTotalElements(),
data.getTotalPages());
return ResponseEntity.ok(wrap(projectionData, pageMetadata));
}
这样就实现了对字段模糊查询和投影外键。