将可选参数传递给Spring Data Repository方法的@Query [英] Passing optional parameters to @Query of a Spring Data Repository method
问题描述
我在当前项目中使用Spring Data和Neo4j并处于以下情况:
I work with Spring Data and Neo4j in my current project and have the following situation:
@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都加倍,并向我的PersonRepository中添加新的find-Methods.所有的find方法都使用Spring @Query注释进行注释,并获得一个自定义的密码查询来获取数据.
You probably already can see my problem: the chain of if-else-blocks. Each time I add a new filter for searching for persons, I have to add new optional parameter, double all the if-else-blocks and add new find-Methods to my PersonRepository. All the find-Methods are annotated with Spring @Query annotation and get a custom cypher query to get the data.
是否可以以更优雅的方式实现此功能?在这种情况下,Spring Data是否提供任何支持?
Is it possible to implement this functionality in a more elegant way? Does Spring Data offer any support in such situation?
推荐答案
我使用带有Spring Data的QueryDSL解决了这个问题.
baeldung.com 上有一个很好的教程.
使用QueryDSL,您的spring数据查询就是personRepository.findAll(predicate);
.
I solved this problem using QueryDSL with Spring Data.
There is a good tutorial on baeldung.com.
With QueryDSL your spring data query is simply personRepository.findAll(predicate);
.
您可以使用一个对象来表示多个请求参数,并将其类型声明为Optional<String> name;
等.
You can use an object to represent the multiple request parameters and declare their type to be Optional<String> name;
etc.
然后您可以构建谓词(假设您已按照链接教程中的说明进行了设置):
Then you can build the predicate (assuming you setup you stuff as in the linked tutorial):
Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();
我亲自对其进行了修改,因此它不使用:",因为它们对我的使用是多余的.
I personally modified it so it didn't use the ":" as they are redundant for my usage.
这篇关于将可选参数传递给Spring Data Repository方法的@Query的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!