gpt4 book ai didi

spring - 将可选参数传递给 Spring Data Repository 方法的 @Query

转载 作者:行者123 更新时间:2023-12-04 21:33:15 25 4
gpt4 key购买 nike

我在当前项目中使用 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 加倍,并向我的 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();

我个人修改了它,所以它没有使用“:”,因为它们对我的使用来说是多余的。

关于spring - 将可选参数传递给 Spring Data Repository 方法的 @Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com