有没有更好的方法来处理过滤器?



JAX-RS with SpringBootApplication.

我正在构建一个API,我想让用户在拉取数据时使用过滤器。如果他们执行GET请求:

http://localhost:8100/apis/employee/?firstName=john&lastName=doe

API 将返回一个或多个满足这些要求的结果。 我还希望他们能够只使用其中一个参数(名字或姓氏)。 我能够编写代码并且它工作得很好,但是只有两个参数,我已经有三种可能的组合(我的 API 上的三种查询方法)。

firstName = NULL && lastName = NULL (getAllEmployees case)
firstName != NULL && lastName = NULL
firstName = NULL && lastName != NULL
firstName != NULL && lastName != NULL

这是我在 employeeResource 文件上的 GET 方法的样子:

@GET
@QueryParam("{firstName}, {lastName}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getEmployees(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName) {
List<Employee> employeeList;
if(firstName != null && !firstName.isEmpty() && lastName != null && !lastName.isEmpty()) {
employeeList = employeeRepository.findByFirstNameAndLastName(firstName, lastName);
}
else if(firstName != null && !firstName.isEmpty()) {
employeeList = employeeRepository.findByFirstName(firstName);
}
else if (lastName != null && !lastName.isEmpty()) {
employeeList = employeeRepository.findByLastName(lastName);
}
else {
employeeList = (List<Employee>) employeeRepository.findAll();
}
if (employeeList.size() == 0) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(employeeList).build();
}

这就是我的 employeeRepository 文件的样子:

public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Integer>{
List<Employee> findByFirstName(String firstName);
List<Employee> findByFirstNameAndLastName(String firstName, String lastName);
List<Employee> findByLastName(String lastName);
}

如果我添加第三个参数,现在可能的组合场景将是 8,所以我需要在employeeRepository上定义 8 个查询函数,您可以想象如果您有 10 个可能的参数要搜索会发生什么。

有没有更好的方法来实现这一点,而不必定义所有这些方法?

我不介意写它们,我只是不想做一些不是最好方法的事情。

如果你想在存储库中使用更通用的查找方法,可以使用规范模式。这是一篇在 java 中实现规范模式的文章。如果需要在 REST 终结点上使用更通用的筛选器,可以查看 OData 如何设置其查询字符串筛选器的格式。

您可以在 EmployeeRepository 上编写自定义查询,如下所示

@Query(" 从员工 e 中选择 e,其中 (:firstName 为 null 或 e.firstName=:firstName) AND (:lastName 为 null 或 e.lastName=:lastName) ") List findByDifferentParams(@Param("firstName)String firstName, @Param("lastName)String lastName);

如果需要,可以添加其他参数。

最新更新