【问题标题】:Passing optional parameters to @Query of a Spring Data Repository method将可选参数传递给 Spring Data Repository 方法的 @Query
【发布时间】: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 在这种情况下是否提供任何支持?

【问题讨论】:

标签: spring spring-data cypher spring-data-neo4j software-design


【解决方案1】:

我使用带有 Spring Data 的 QueryDSL 解决了这个问题。 baeldung.com 上有一个很好的教程。 使用 QueryDSL,您的 spring 数据查询只需 personRepository.findAll(predicate);

您可以使用一个对象来表示多个请求参数并将它们的类型声明为Optional&lt;String&gt; name;等。

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

Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();

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

【讨论】:

  • 你好@AllanT!这对我来说似乎是一个完美的解决方案。不幸的是,Spring Data Neo4J 在当前版本中似乎已经弃用了对 QueryDslPredicateExecutor 的支持
猜你喜欢
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
相关资源
最近更新 更多