使用弹簧启动设计新应用程序时。我希望有一个休息终点来找到所有具有下面过滤器的实体
获取http://foo.com/entities?firstName=test&lastName=test2
实现如下所示。
@RequestMapping(value = /entities, method = RequestMethod.GET)
public List<Entity> getAll(@RequestParam(value = "firstName", required = false) String firstName, @RequestParam(value = "lastName", required = false) String lastName) {
if (firstName != null && lastName != null) {
return entityRepository.findByFirstNameAndLastName(firstName, lastName);
} else if (firstName != null) {
return entityRepository.findByFirstName(firstName);
} else if (lastName != null) {
return entityRepository.findByLastName(lastName);
} else {
return StreamSupport.stream(entityRepository.findAll().spliterator(), false).collect(Collectors.toList());
}
}
如果我们必须添加新参数,我们可以看到这有点失控。减轻这种情况的最简单方法是什么?或者我应该改变设计。我认为这是标准做法?
请注意。存储库是一个带有添加方法的CRUDRepository。
答案 0 :(得分:0)
我认为您应该创建某种“SearchUtils”并使用Criteria API。 例如:
public class SearchCriteria {
public SearchCriteria() {
}
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
SearchUtils类:
public class SearchUtils {
List<Entity> search(SearchCriteria criteria){
//use Criteria API here
}
}
和控制器:
@RequestMapping(value = /entities, method = RequestMethod.GET)
public List<Entity> getAll(@Valid SearchCriteria searchCriteria)
{
return searchUtils.search(searchCriteria);
}
答案 1 :(得分:-1)