Spring Boot 2.x实战74 - Spring Data 18 - Spring Data Elasticsearch查询(根据实体属性名推导查询)与原生查询(@Query)

3.6 查询

3.6.1 查询方法

我们在PersonRepository内定义查询方法,这里的查询和Spring Data JPA推导查询保持一致。

public interface PersonRepository extends ElasticsearchRepository<Person,String> {
    List<Person> findByName(String name); //1
    
    List<Person> findByAddress_City(String city); //2
    
    List<Person> findByChildren_Name(String childName); //3
    
    @Query("{\"bool\" : {\"must\" : {\"range\" : {\"age\" : {\"gte\" : \"?0\", \"lte\" : \"?1\"}}}}}")
    Page<Person> findByAgeRange(Integer startAge, Integer endAge, Pageable pageable); //3
}
  1. 通过值name查询;
  2. 通过值对象Addresscity属性查询;
  3. 通过列表值对象childrenname查询;
  4. 通过@Query使用Elasticsearch查询自定义语言,查询agestartAgeendAge之间的Person,并使用分页和排序功能。

通过代码验证:

@Bean
CommandLineRunner query(PersonRepository personRepository){
   return args -> {
      List<Person> people1 = personRepository.findByName("wyf");
      List<Person> people2 = personRepository.findByAddress_City("bei jing");
      List<Person> people3 = personRepository.findByChildren_Name("ccc");
      Page<Person> personPage = personRepository.findByAgeRange(30, 40,
            PageRequest.of(0,3, Sort.by(Sort.Direction.DESC,"age")));
      people1.forEach(System.out::println);
      people2.forEach(System.out::println);
      people3.forEach(System.out::println);
      System.out.println("总数为: " + personPage.getTotalElements()
            + " 总页数为:" + personPage.getTotalPages());
      personPage.forEach(System.out::println);
   };
}

在这里插入图片描述

新书推荐:

我的新书《从企业级开发到云原生微服务: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/106707687
今日推荐