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

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

上一篇文章介绍了 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 {
   
    @Id
    private 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. 减少代码复杂度:自动实现常用的数据库操作,减少重复代码ÿ
评论 84
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CoderJia_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值