欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Data Jpa 学习之 QueryByExampleExecutor 接口

程序员文章站 2022-07-14 09:26:09
...

JpaRepository 接口通过继承 QueryByExampleExecutor 实现简单的动态查询功能

创建 Entity

@Entity
@Data
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String company;
    private String address;
}

创建接口

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

创建测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository;

    @Test
    public void simpleTest() {
        Person person = new Person();
        person.setName("linan");

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

        Optional<Person> one = personRepository.findOne(example);
    }

    @Test
    public void matcherTest() {
        Person person = new Person();
        person.setName("linan");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnorePaths("name")
                .withIncludeNullValues()
                .withStringMatcher(ExampleMatcher.StringMatcher.ENDING);

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

        Optional<Person> one = personRepository.findOne(example);

    }

    @Test
    public void configMatcherTest() {
        Person person = new Person();
        person.setName("linan");
        person.setCompany("海");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", endsWith())
                .withMatcher("company", startsWith().ignoreCase());

        Example<Person> example = Example.of(person, matcher);
        List<Person> all = personRepository.findAll(example);
        all.forEach(x -> System.out.println(x));
    }

    @Test
    public void configMatcherLambdaTest() {
        Person person = new Person();
        person.setName("linan");
        person.setCompany("海");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", match -> match.endsWith())
                .withMatcher("company", match -> match.startsWith().ignoreCase());

        Example<Person> example = Example.of(person, matcher);
        List<Person> all = personRepository.findAll(example);
        all.forEach(System.out::println);
    }
}

StringMatcher options

Spring Data Jpa 学习之 QueryByExampleExecutor 接口