Ira*_* Re 5 spring software-design cypher spring-data spring-data-neo4j
我在当前项目中使用Spring Data和Neo4j并处于以下情况:
@RestController
@RequestMapping(value = SearchResource.URI)
public class PersonResource {
public static final String URI = "/person";
@Autowired
PersonRepository personRepository;
@GetMapping
public Collection<Person> findPersons(
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "birthDate", required = false) Long birthDate,
@RequestParam(value = "town", required = false) Spring town) {
Collection<Person> persons;
if (name != null && birthDate == null && town == null) {
persons = personRepository.findPersonByName(name);
} else if (name != null && birthDate != null && town == null {
persons = personRepository.findPersonByNameAndBirthDate(name, birthDate);
} else if (name != null && birthDate != null && town != null {
persons = personRepository.findPersonByNameAndBirthDateAndTown(name, birthDate, town);
} else if (name == null && birthDate != null && town == null {
persons = findPersonByBirthDate(birthDate);
} else if
...
}
return persons;
}
}
Run Code Online (Sandbox Code Playgroud)
您可能已经看到了我的问题:if-else-blocks链。每次我添加一个用于搜索人员的新过滤器时,都必须添加新的可选参数,将所有的if-else-blocks都加倍,并向我的PersonRepository添加新的find-Methods。所有的find-Methods都带有Spring @Query注释,并获得一个自定义的密码查询来获取数据。
是否可以以更优雅的方式实现此功能?在这种情况下,Spring Data是否提供任何支持?
我使用 QueryDSL 和 Spring Data 解决了这个问题。baeldung.com上有一个很好的教程。使用 QueryDSL,您的 Spring 数据查询非常简单personRepository.findAll(predicate);。
您可以使用一个对象来表示多个请求参数并声明它们的类型为等Optional<String> name;。
然后您可以构建谓词(假设您按照链接教程中的方式设置内容):
Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();
Run Code Online (Sandbox Code Playgroud)
我亲自修改了它,因此它没有使用“:”,因为它们对我的使用来说是多余的。
| 归档时间: |
|
| 查看次数: |
4403 次 |
| 最近记录: |