SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用
上一篇文章介紹了 Spring Boot 3 整合 Elasticsearch 8.x 的幾種客戶端形式,除此之外,Spring Data 對 Elasticsearch 還提供了 Repository 支持,與前面討論的JPA Repository 一樣,其基本原理是根據(jù)方法名稱自動為你構(gòu)建查詢,提供了更簡便的數(shù)據(jù)搜索和分析功能。本文將介紹如何使用 Spring Data Elasticsearch Repository 來構(gòu)建一個(gè)簡單的搜索應(yīng)用。
1. 環(huán)境準(zhǔn)備
1.1 項(xiàng)目依賴
在 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.properties 或 application.yml 中配置 Elasticsearch 的連接信息:
spring:
elasticsearch:
uris: "http://localhost:9200"
socket-timeout: "10s"
username: "user"
password: "secret"2. 使用Repository的基本步驟
2.1 創(chuàng)建實(shí)體類
我們定義一個(gè) Product 實(shí)體類,表示產(chǎn)品信息:
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 創(chuàng)建 Repository 接口
ElasticsearchRepository 是 Spring Data Elasticsearch 提供的一個(gè)接口,用于簡化與 Elasticsearch 交互的操作。它繼承自 CrudRepository 和 PagingAndSortingRepository,擴(kuò)展了基本的 CRUD(創(chuàng)建、讀取、更新、刪除)功能,支持分頁和排序,還提供了對 Elasticsearch 特有的操作支持。使用 ElasticsearchRepository,開發(fā)者可以快速構(gòu)建功能全面的數(shù)據(jù)訪問層,而無需編寫復(fù)雜的 Elasticsearch 客戶端代碼。
2.2.1 主要作用和優(yōu)點(diǎn)
- 簡化數(shù)據(jù)操作:提供了基礎(chǔ)的 CRUD 方法,如
save()、findById()、findAll()和deleteById()等,方便開發(fā)者直接使用。 - 自定義查詢:通過定義接口中的方法(如
findByName(String name)),可以自動生成符合方法命名規(guī)范的查詢。 - 分頁與排序:內(nèi)置了分頁和排序支持,方法如
findAll(Pageable pageable)可以直接返回分頁數(shù)據(jù)。 - 與 Spring 無縫集成:使用 Spring 的依賴注入和配置機(jī)制,無需手動創(chuàng)建或管理客戶端連接。
- 減少代碼復(fù)雜度:自動實(shí)現(xiàn)常用的數(shù)據(jù)庫操作,減少重復(fù)代碼,提高開發(fā)效率。
2.2.2 使用場景
- 需要快速實(shí)現(xiàn)基于 Elasticsearch 的應(yīng)用程序,且不希望編寫底層客戶端調(diào)用代碼。
- 開發(fā)中涉及到簡單或中等復(fù)雜度的查詢,使用方法命名約定生成查詢即可滿足需求。
- 項(xiàng)目中需要分頁、排序功能而不想手動處理分頁邏輯。
定義 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 服務(wù)層實(shí)現(xiàn)
在服務(wù)層中實(shí)現(xiàn)增刪改查的業(yè)務(wù)邏輯:
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 {
@Resource
private ProductRepository productRepository;
// 創(chuàng)建或更新產(chǎn)品
public Product saveProduct(Product product) {
return productRepository.save(product);
}
// 根據(jù) ID 查詢產(chǎn)品
public Optional<Product> findById(String id) {
return productRepository.findById(id);
}
// 根據(jù)名稱查詢產(chǎn)品
public List<Product> findByName(String name) {
return productRepository.findByName(name);
}
// 獲取所有產(chǎn)品
public Page<Product> findAll(Pageable pageable) {
return productRepository.findAll(pageable);
}
// 刪除產(chǎn)品
public void deleteProduct(String id) {
productRepository.deleteById(id);
}
}2.4 控制器層
在控制器層實(shí)現(xiàn) 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 {
@Resource
private ProductService productService;
// 創(chuàng)建或更新產(chǎn)品
@PostMapping
public Product createOrUpdateProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
// 根據(jù) ID 查詢產(chǎn)品
@GetMapping("/{id}")
public Optional<Product> getProductById(@PathVariable String id) {
return productService.findById(id);
}
// 根據(jù)名稱查詢產(chǎn)品
@GetMapping("/search")
public List<Product> searchByName(@RequestParam String name) {
return productService.findByName(name);
}
// 獲取所有產(chǎn)品
@GetMapping
public 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();
}
// 刪除產(chǎn)品
@DeleteMapping("/{id}")
public String deleteProduct(@PathVariable String id) {
productService.deleteProduct(id);
return "Product deleted successfully!";
}
}3. 測試應(yīng)用
3.1 啟動 Elasticsearch
確保 Elasticsearch 8.x 正在運(yùn)行,并且可以通過 http://localhost:9200 訪問。
3.2 啟動 Spring Boot 應(yīng)用
運(yùn)行 Spring Boot 應(yīng)用,確保沒有錯(cuò)誤。
3.3 測試 API
創(chuàng)建產(chǎn)品:
POST http://localhost:8080/products
Content-Type: application/json
{
"id": "1",
"name": "coderjia",
"description": "desc v1",
"price": 1.0
}
更新產(chǎn)品:
POST http://localhost:8080/products
Content-Type: application/json
{
"id": "1",
"name": "coderjia",
"description": "desc v2",
"price": 2.0
}
根據(jù) ID 查詢產(chǎn)品:
GET http://localhost:8080/products/1

根據(jù)名稱查詢產(chǎn)品:
GET http://localhost:8080/products/search?name=coderjia

獲取所有產(chǎn)品(分頁):
GET http://localhost:8080/products?page=0&size=3

刪除產(chǎn)品:
DELETE http://localhost:8080/products/1

4. 總結(jié)
通過以上步驟,我們構(gòu)建了一個(gè)完整的 Spring Boot 3 和 Elasticsearch 8.x 的增刪改查示例應(yīng)用。使用 Spring Data Elasticsearch Repository,我們能夠快速實(shí)現(xiàn)對 Elasticsearch 的基本 CRUD 操作,簡化了開發(fā)流程。希望這個(gè)示例能夠幫助你理解如何在項(xiàng)目中有效使用 Elasticsearch!
到此這篇關(guān)于SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用的文章就介紹到這了,更多相關(guān)SpringBoot3整合 Elasticsearch 8.x內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于IDEA 2020使用 mybatis-log-plugin插件的問題
這篇文章主要介紹了關(guān)于IDEA 2020使用 mybatis-log-plugin插件的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
關(guān)于Idea使用git時(shí)commit特別慢的問題及解決方法
這篇文章主要介紹了關(guān)于Idea使用git時(shí)commit特別慢的問題及解決方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
IDEA創(chuàng)建javaee項(xiàng)目依賴war exploded變紅失效的解決方案
在使用IntelliJ IDEA創(chuàng)建JavaEE項(xiàng)目時(shí),可能會遇到Tomcat部署的warexploded文件出現(xiàn)問題,解決方法是首先刪除有問題的warexploded依賴,然后根據(jù)圖示重新導(dǎo)入項(xiàng)目,此外,調(diào)整虛擬路徑有時(shí)也能有效解決問題2024-09-09
spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解
這篇文章主要為大家介紹了spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
SpringCloud整合OpenFeign實(shí)現(xiàn)微服務(wù)間的通信
微服務(wù)之間的通信?式,通常有兩種: RPC 和 HTTP,在SpringCloud中, 默認(rèn)是使?HTTP來進(jìn)?微服務(wù)的通信, 最常?的實(shí)現(xiàn)形式有兩種:RestTemplate和OpenFeign,本文給大家介紹了SpringCloud整合OpenFeign實(shí)現(xiàn)微服務(wù)間的通信,需要的朋友可以參考下2024-06-06

