将可选参数传递给Spring数据存储库方法的@Query

将可选参数传递给Spring数据存储库方法的@Query,spring,spring-data,cypher,spring-data-neo4j,software-design,Spring,Spring Data,Cypher,Spring Data Neo4j,Software Design,我在当前的项目中使用Spring Data和Neo4j,并有以下情况: @RestController @RequestMapping(value = SearchResource.URI) public class PersonResource { public static final String URI = "/person"; @Autowired PersonRepository personRepository; @GetMapping public Collection&l

我在当前的项目中使用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;
}
}
@RestController
@RequestMapping(值=SearchResource.URI)
公共类人员资源{
公共静态最终字符串URI=“/person”;
@自动连线
个人知识库;
@GetMapping
公共收集查找人员(
@RequestParam(value=“name”,required=false)字符串名称,
@RequestParam(value=“birthDate”,required=false)长生日,
@RequestParam(value=“town”,required=false)Spring town){
收款人;
如果(姓名!=null&&birthDate==null&&town==null){
persons=personRepository.findPersonByName(name);
}如果(name!=null&&birthDate!=null&&town==null),则为else{
persons=personRepository.findpersonbyname和birthDate(姓名、生日);
}如果(name!=null&&birthDate!=null&&town!=null,则为else{
persons=personRepository.findPersonByNameAndBirthDateAndTown(姓名、出生日期、城镇);
}else如果(name==null&&birthDate!=null&&town==null{
persons=按出生日期查找Person(出生日期);
}否则如果
...
}
返回人员;
}
}
您可能已经看到了我的问题:if-else块的链。每次我添加一个新的用于搜索人员的筛选器时,我都必须添加新的可选参数,将所有if-else块加倍,并将新的find方法添加到我的PersonRepository中。所有find方法都使用Spring@Query注释进行注释,并获得一个自定义的cypher查询以获得t他收集数据


是否有可能以更优雅的方式实现此功能?Spring数据在这种情况下是否提供任何支持?

我使用带有Spring数据的QueryDSL解决了此问题。 有一个很好的教程。 使用QueryDSL,您的spring数据查询就是
personRepository.findAll(谓词);

您可以使用一个对象来表示多个请求参数,并将其类型声明为
可选名称;

然后,您可以构建谓词(假设您按照链接教程中的设置进行填充):


我个人对其进行了修改,因此它没有使用“:”,因为它们对于我的使用是多余的。

为您的存储库定义一个自定义方法()。在方法实现中,根据搜索条件动态生成查询,并执行它。您可以尝试使用这种方法Hello@AllanT!这对我来说似乎是一个完美的解决方案。不幸的是,Spring Data Neo4J似乎不赞成当前版本中对QueryDslPredicateExecutor的支持
Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();