Spring Boot 2.x实战66 - Spring Data 10 - Spring Data JPA动态条件组合查询Query by Example

2.6.4 Query by Example

Qurery by Example简称QBE,它会根据部分属性已经设置的实体,动态进行查询。它主要分为3个部分:

  • Probe:设置属性的实体;
  • ExampleMatcher:对于实体的属性的匹配规则的设置;
  • Example :组合Probe和ExampleMatcher进行查询。

直接看代码:

@Bean
CommandLineRunner queryByExample(PersonRepository personRepository){
   return args -> {
      Person person = new Person();
      person.setName("Y"); //1

      ExampleMatcher matcher = ExampleMatcher.matching() //2
            .withIgnoreCase("name") //3
            .withStringMatcher(StringMatcher.CONTAINING); //4

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

      List<Person> people = personRepository.findAll(example); //6
      people.forEach(System.out::println);

   };
}
  1. 构造Probe设置name属性的值,此处设置的为大写的Y
  2. 构造ExampleMatcher对象;
  3. name属性匹配的时候忽略大小写;
  4. 字符类型匹配模式使用包含;
  5. 使用Probe和ExampleMatcher构造Example
  6. 使用Example作为参数进行查询。
    在这里插入图片描述

新书推荐:

我的新书《从企业级开发到云原生微服务:Spring Boot 实战》已出版,内容涵盖了丰富Spring Boot开发的相关知识
购买地址:https://item.jd.com/12760084.html
在这里插入图片描述

主要包含目录有:

第一章 初识Spring Boot(快速领略Spring Boot的美丽)
第二章 开发必备工具(对常用开发工具进行介绍:包含IntelliJ IDEA、Gradle、Lombok、Docker等)
第三章 函数式编程
第四章 Spring 5.x基础(以Spring 5.2.x为基础)
第五章 深入Spring Boot(以Spring Boot 2.2.x为基础)
第六章 Spring Web MVC
第七章 数据访问(包含Spring Data JPA、Spring Data Elasticsearch和数据缓存)
第八章 安全控制(包含Spring Security和OAuth2)
第九章 响应式编程(包含Project Reactor、Spring WebFlux、Reactive NoSQL、R2DBC、Reactive Spring Security)
第十章 事件驱动(包含JMS、RabbitMQ、Kafka、Websocket、RSocket)
第11章 系统集成和屁股里(包含Spring Integration和Spring Batch)
第12章 Spring Cloud与微服务
第13章 Kubernetes与微服务(包含Kubernetes、Helm、Jenkins、Istio)
多谢大家支持。

猜你喜欢

转载自blog.csdn.net/wiselyman/article/details/106516267