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

Wildcard Field QueryByExample with JPA Repositories

我有以下 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() 以使其不区分大小写。

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

替代语法(更短)。

服务方式:

public Page<PersonDto> listPersons(Person probe, Pageable pageable) {
    ExampleMatcher matcher = ExampleMatcher.matching()
        .withIgnoreCase()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

    final Example<Person> example = Example.of(probe, matcher);
    return personRepository.findAll(example, pageable)
            .map(PersonMapper::convertToDto);
}

存储库:

@Repository
public interface PersonRepository extends JpaRepository<Person, Long>, QueryByExampleExecutor<Person> {
}