【发布时间】:2018-01-24 19:05:15
【问题描述】:
我在当前项目中使用 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;
}
}
您可能已经看到了我的问题:if-else-blocks 链。每次我添加一个用于搜索人员的新过滤器时,我都必须添加新的可选参数,将所有 if-else-blocks 加倍并将新的 find-Methods 添加到我的 PersonRepository。所有 find-Methods 都使用 Spring @Query 注解进行注解,并通过自定义密码查询来获取数据。
是否有可能以更优雅的方式实现此功能? Spring Data 在这种情况下是否提供任何支持?
【问题讨论】:
-
为您的存储库定义自定义方法 (docs.spring.io/spring-data/neo4j/docs/4.2.6.RELEASE/reference/…)。在方法实现中,根据搜索条件动态生成查询,并执行。
-
你可以尝试使用这种方法stackoverflow.com/a/44705452
-
我在这里发布了一个答案:stackoverflow.com/a/69362813/7189597 这个解决方案看起来比我在 stackoverflow 或 web 上找到的其他解决方案更简单有效。看看!!!你会喜欢的;)
标签: spring spring-data cypher spring-data-neo4j software-design