重学SpringBoot3-整合 Elasticsearch 8.x (二)使用Repository

devtools/2025/2/10 14:21:55/

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞??收藏评论

整合 Elasticsearch 8.x (二)使用Repository
  • 1. 环境准备
    • 1.1 项目依赖
    • 1.2 Elasticsearch 配置
  • 2. 使用Repository的基本步骤
    • 2.1 创建实体类
    • 2.2 创建 Repository 接口
      • 2.2.1 主要作用和优点
      • 2.2.2 使用场景
    • 2.3 服务层实现
    • 2.4 控制器层
  • 3. 测试应用
    • 3.1 启动 Elasticsearch
    • 3.2 启动 Spring Boot 应用
    • 3.3 测试 API
  • 4. 总结

上一篇文章介绍了 Spring Boot 3 整合 Elasticsearch 8.x 的几种客户端形式,除此之外,Spring Data 对 Elasticsearch 还提供了 Repository 支持,与前面讨论的JPA Repository 一样,其基本原理是根据方法名称自动为你构建查询,提供了更简便的数据搜索和分析功能。本文将介绍如何使用 Spring Data Elasticsearch Repository 来构建一个简单的搜索应用。

1. 环境准备

1.1 项目依赖

pom.xml 中添加以下依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

确保 spring-boot-starter-data-elasticsearch 的版本与 Spring Boot 3 兼容。

1.2 Elasticsearch 配置

application.propertiesapplication.yml 中配置 Elasticsearch 的连接信息:

spring:elasticsearch:uris: "http://localhost:9200"socket-timeout: "10s"username: "user"password: "secret"

2. 使用Repository的基本步骤

2.1 创建实体类

我们定义一个 Product 实体类,表示产品信息:

package com.coderjia.boot318es.bean;import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;/*** @author CoderJia* @create 2024/11/3 下午 04:37* @Description**/
@Data
@Document(indexName = "products")
@AllArgsConstructor
public class Product {@Idprivate String id;private String name;private String description;private double price;
}

2.2 创建 Repository 接口

ElasticsearchRepository 是 Spring Data Elasticsearch 提供的一个接口,用于简化与 Elasticsearch 交互的操作。它继承自 CrudRepositoryPagingAndSortingRepository,扩展了基本的 CRUD(创建、读取、更新、删除)功能,支持分页和排序,还提供了对 Elasticsearch 特有的操作支持。使用 ElasticsearchRepository,开发者可以快速构建功能全面的数据访问层,而无需编写复杂的 Elasticsearch 客户端代码。

2.2.1 主要作用和优点
  1. 简化数据操作:提供了基础的 CRUD 方法,如 save()findById()findAll()deleteById() 等,方便开发者直接使用。
  2. 自定义查询:通过定义接口中的方法(如 findByName(String name)),可以自动生成符合方法命名规范的查询。
  3. 分页与排序:内置了分页和排序支持,方法如 findAll(Pageable pageable) 可以直接返回分页数据。
  4. 与 Spring 无缝集成:使用 Spring 的依赖注入和配置机制,无需手动创建或管理客户端连接。
  5. 减少代码复杂度:自动实现常用的数据库操作,减少重复代码,提高开发效率。
2.2.2 使用场景
  • 需要快速实现基于 Elasticsearch 的应用程序,且不希望编写底层客户端调用代码。
  • 开发中涉及到简单或中等复杂度的查询,使用方法命名约定生成查询即可满足需求。
  • 项目中需要分页、排序功能而不想手动处理分页逻辑。

定义 ProductRepository 接口,继承 ElasticsearchRepository

package com.coderjia.boot318es.dao;import com.coderjia.boot318es.bean.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;import java.util.List;/*** @author CoderJia* @create 2024/11/4 下午 09:29* @Description**/
public interface ProductRepository extends ElasticsearchRepository<Product, String> {/*** 自定义通过name查询** @param name* @return*/List<Product> findByName(String name);
}

2.3 服务层实现

在服务层中实现增删改查的业务逻辑:

package com.coderjia.boot318es.service;import com.coderjia.boot318es.bean.Product;
import com.coderjia.boot318es.dao.ProductRepository;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Optional;/*** @author CoderJia* @create 2024/11/4 下午 09:29* @Description**/
@Service
public class ProductService {@Resourceprivate ProductRepository productRepository;// 创建或更新产品public Product saveProduct(Product product) {return productRepository.save(product);}// 根据 ID 查询产品public Optional<Product> findById(String id) {return productRepository.findById(id);}// 根据名称查询产品public List<Product> findByName(String name) {return productRepository.findByName(name);}// 获取所有产品public Page<Product> findAll(Pageable pageable) {return productRepository.findAll(pageable);}// 删除产品public void deleteProduct(String id) {productRepository.deleteById(id);}
}

2.4 控制器层

在控制器层实现 REST API 接口,处理增删改查请求:

package com.coderjia.boot318es.controller;import com.coderjia.boot318es.bean.Product;
import com.coderjia.boot318es.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.Optional;/*** @author CoderJia* @create 2024/11/4 下午 09:30* @Description**/
@RestController
@RequestMapping("/products")
public class ProductController {@Resourceprivate ProductService productService;// 创建或更新产品@PostMappingpublic Product createOrUpdateProduct(@RequestBody Product product) {return productService.saveProduct(product);}// 根据 ID 查询产品@GetMapping("/{id}")public Optional<Product> getProductById(@PathVariable String id) {return productService.findById(id);}// 根据名称查询产品@GetMapping("/search")public List<Product> searchByName(@RequestParam String name) {return productService.findByName(name);}// 获取所有产品@GetMappingpublic List<Product> getAllProducts(@RequestParam(defaultValue = "0") int page,@RequestParam(defaultValue = "10") int size) {Pageable pageable = PageRequest.of(page, size);Page<Product> products = productService.findAll(pageable);return products.getContent();}// 删除产品@DeleteMapping("/{id}")public String deleteProduct(@PathVariable String id) {productService.deleteProduct(id);return "Product deleted successfully!";}
}

3. 测试应用

3.1 启动 Elasticsearch

确保 Elasticsearch 8.x 正在运行,并且可以通过 http://localhost:9200 访问。

3.2 启动 Spring Boot 应用

运行 Spring Boot 应用,确保没有错误。

3.3 测试 API

创建产品

POST http://localhost:8080/products
Content-Type: application/json{"id": "1","name": "coderjia","description": "desc v1","price": 1.0
}

创建产品

更新产品

POST http://localhost:8080/products
Content-Type: application/json{"id": "1","name": "coderjia","description": "desc v2","price": 2.0
}

更新产品

根据 ID 查询产品

GET http://localhost:8080/products/1

根据 ID 查询产品

根据名称查询产品

GET http://localhost:8080/products/search?name=coderjia

根据名称查询产品

获取所有产品(分页)

GET http://localhost:8080/products?page=0&size=3

分页查询

删除产品

DELETE http://localhost:8080/products/1

删除产品

4. 总结

通过以上步骤,我们构建了一个完整的 Spring Boot 3 和 Elasticsearch 8.x 的增删改查示例应用。使用 Spring Data Elasticsearch Repository,我们能够快速实现对 Elasticsearch 的基本 CRUD 操作,简化了开发流程。希望这个示例能够帮助你理解如何在项目中有效使用 Elasticsearch!


http://www.ppmy.cn/devtools/157343.html

相关文章

【PyQt】集中式样式表(QSS文件)管理界面样式

集中式样式表&#xff08;QSS文件&#xff09;管理界面样式 集中式样式表&#xff08;通常使用QSS&#xff0c;Qt StyleSheet&#xff09;是一种非常有效的方式来管理和定制你的PyQt应用程序的界面样式。类似于Web开发中的CSS&#xff0c;QSS允许你以声明式的方式定义组件的外…

每日一道算法题

题目&#xff1a;单词接龙 II 给定两个单词&#xff08;beginWord 和 endWord&#xff09;和一个字典 wordList&#xff0c;找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则&#xff1a; 每次转换只能改变一个字母。转换过程中的中间单词必须是字典中的…

Flutter完整开发实战详解(六、 深入Widget原理)

Flutter 番外的世界系列文章专栏 首先我们需要明白&#xff0c;Widget 是什么&#xff1f;这里有一个 “总所周知” 的答就是&#xff1a;Widget并不真正的渲染对象 。是的&#xff0c;事实上在 Flutter 中渲染是经历了从 Widget 到 Element 再到 RenderObject 的过程。 我们都…

SpringBoot高级-底层原理

目录 1 SpringBoot自动化配置原理 01-SpringBoot2高级-starter依赖管理机制 02-SpringBoot2高级-自动化配置初体验 03-SpringBoot2高级-底层原理-Configuration配置注解 04-SpringBoot2高级-底层原理-Import注解使用1 05-SpringBoot2高级-底层原理-Import注解使用2 06-S…

内核日志查看:dmesg命令

dmesg 是 Linux 系统中用于 查看或控制内核环形缓冲区 的命令行工具。它主要用于显示系统启动时的硬件检测信息、内核日志以及运行时的硬件/驱动相关事件&#xff08;如 USB 设备插拔、磁盘挂载等&#xff09;。以下是 dmesg 的详细说明&#xff1a; 基本功能 查看内核日志&am…

基于ansible自动化部署ftp服务

Ansible部署FTP服务 基础环境配置就不过多赘述了 配置主机名、主机解析、免密访问、ansible下载、配置ansible主机、防火墙、selinux、配置centos2009镜像为仓库源、配置ftp远程仓库&#xff1a;可参考博文 节点信息如下&#xff1a; 主机名IPansible192.168.200.75node192…

RabbitMQ 从入门到精通:从工作模式到集群部署实战(二)

接上篇&#xff1a;《RabbitMQ 从入门到精通&#xff1a;从工作模式到集群部署实战&#xff08;一&#xff09;》 链接 文章目录 4.安装RabbitMQ Messaging Topology Operator 裸金属环境部署RabbitMQ部署单实例部署集群 4.安装RabbitMQ Messaging Topology Operator 使用 cer…

string 与 wstring 的字符编码

测试代码: #include<stdio.h> #include<stdlib.h> #include<windows.h> #include <locale.h> #include <string> #include <iostream>// 函数用于计算UTF-8字符串中的字符数 int utf8_strlen(const char* str) {int len = 0;for (; *s…