我使用Query by Example实现了此功能。
假设您有以下模型:
@Entity
public class Company {
@Id
@GeneratedValue
Long id;
String name;
String address;
@ManyToOne
Department department;
}
@Entity
public class Department {
@Id
@GeneratedValue
Long id;
String name;
}
还有代码库:
@RepositoryRestResource
public interface CompanyRepository extends JpaRepository<Company, Long> {
}
请注意,JpaRepository 实现了 QueryByExampleExecutor。
现在您需要实现一个自定义控制器:
@RepositoryRestController
@RequiredArgsConstructor
public class CompanyCustomController {
private final CompanyRepository repository;
@GetMapping("/companies/filter")
public ResponseEntity<?> filter(
Company company,
Pageable page,
PagedResourcesAssembler assembler,
PersistentEntityResourceAssembler entityAssembler
){
ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnoreCase()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
Example example = Example.of(company, matcher);
Page<?> result = this.repository.findAll(example, page);
return ResponseEntity.ok(assembler.toResource(result, entityAssembler));
}
}
然后你可以像这样查询:
localhost:8080/companies/filter?name=google&address=NY
您甚至可以查询嵌套实体,例如:
localhost:8080/companies/filter?name=google&department.name=finances
为了简洁起见,我省略了一些细节,但是我在Github上创建了一个工作示例。