gpt4 book ai didi

java - 使用 JPA 存储库的通配符字段 QueryByExample

转载 作者:行者123 更新时间:2023-11-30 06:23:08 26 4
gpt4 key购买 nike

我有以下 JPA 存储库:

public interface PostRepository extends JpaRepository<Post, String> {

List<Post> findAll();

List<Post> findByExample(Example<Post> example);
}

我需要修改 findByExample 以获取示例,但在单个字段上使用通配符。因此,在本例中,字段“title”需要相当于 SQL 的“like”或“contains”。

Spring 文档显示了这一点:

Person person = new Person();                          
person.setFirstname("Dave");

ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnorePaths("lastname")
.withIncludeNullValues()
.withStringMatcherEnding();

Example<Person> example = Example.of(person, matcher);

来自 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods

但我不确定如何自定义我的界面(假设是默认方法)来使用它。

或者是否有一个方法的特定名称,spring将使用此功能自动配置,例如

List<Post> findByExampleTitleLike(Example<Post> example);

TIA

最佳答案

我这样做:

Person person = ...
PageRequest page = ...
ExampleMatcher matcher = ExampleMatcher.matching().withMatcher(
"lastname",
ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.CONTAINING).ignoreCase()
);
return personRepository.findByExample(Example.of(person, matcher), page).getContent();

SQL“like”或“contains”StringMatcher.CONTAINING完成。另外我添加了ignoreCase()以使其不区分大小写。

如果有人知道更短的语法,我很乐意看到:)

关于java - 使用 JPA 存储库的通配符字段 QueryByExample,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729309/

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