SpringBoot3整合 Elasticsearch 8.x 使用Repository構建增刪改查示例應用
上一篇文章介紹了 Spring Boot 3 整合 Elasticsearch 8.x 的幾種客戶端形式,除此之外,Spring Data 對 Elasticsearch 還提供了 Repository 支持,與前面討論的JPA Repository 一樣,其基本原理是根據方法名稱自動為你構建查詢,提供了更簡便的數(shù)據搜索和分析功能。本文將介紹如何使用 Spring Data Elasticsearch Repository 來構建一個簡單的搜索應用。
1. 環(huán)境準備
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.properties
或 application.yml
中配置 Elasticsearch 的連接信息:
spring: elasticsearch: uris: "http://localhost:9200" socket-timeout: "10s" username: "user" password: "secret"
2. 使用Repository的基本步驟
2.1 創(chuàng)建實體類
我們定義一個 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 創(chuàng)建 Repository 接口
ElasticsearchRepository
是 Spring Data Elasticsearch 提供的一個接口,用于簡化與 Elasticsearch 交互的操作。它繼承自 CrudRepository
和 PagingAndSortingRepository
,擴展了基本的 CRUD(創(chuàng)建、讀取、更新、刪除)功能,支持分頁和排序,還提供了對 Elasticsearch 特有的操作支持。使用 ElasticsearchRepository
,開發(fā)者可以快速構建功能全面的數(shù)據訪問層,而無需編寫復雜的 Elasticsearch 客戶端代碼。
2.2.1 主要作用和優(yōu)點
- 簡化數(shù)據操作:提供了基礎的 CRUD 方法,如
save()
、findById()
、findAll()
和deleteById()
等,方便開發(fā)者直接使用。 - 自定義查詢:通過定義接口中的方法(如
findByName(String name)
),可以自動生成符合方法命名規(guī)范的查詢。 - 分頁與排序:內置了分頁和排序支持,方法如
findAll(Pageable pageable)
可以直接返回分頁數(shù)據。 - 與 Spring 無縫集成:使用 Spring 的依賴注入和配置機制,無需手動創(chuàng)建或管理客戶端連接。
- 減少代碼復雜度:自動實現(xiàn)常用的數(shù)據庫操作,減少重復代碼,提高開發(fā)效率。
2.2.2 使用場景
- 需要快速實現(xiàn)基于 Elasticsearch 的應用程序,且不希望編寫底層客戶端調用代碼。
- 開發(fā)中涉及到簡單或中等復雜度的查詢,使用方法命名約定生成查詢即可滿足需求。
- 項目中需要分頁、排序功能而不想手動處理分頁邏輯。
定義 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 服務層實現(xiàn)
在服務層中實現(xiàn)增刪改查的業(yè)務邏輯:
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)建或更新產品 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 控制器層
在控制器層實現(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)建或更新產品 @PostMapping public 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); } // 獲取所有產品 @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(); } // 刪除產品 @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
創(chuàng)建產品:
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
根據名稱查詢產品:
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,我們能夠快速實現(xiàn)對 Elasticsearch 的基本 CRUD 操作,簡化了開發(fā)流程。希望這個示例能夠幫助你理解如何在項目中有效使用 Elasticsearch!
到此這篇關于SpringBoot3整合 Elasticsearch 8.x 使用Repository構建增刪改查示例應用的文章就介紹到這了,更多相關SpringBoot3整合 Elasticsearch 8.x內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于IDEA 2020使用 mybatis-log-plugin插件的問題
這篇文章主要介紹了關于IDEA 2020使用 mybatis-log-plugin插件的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11IDEA創(chuàng)建javaee項目依賴war exploded變紅失效的解決方案
在使用IntelliJ IDEA創(chuàng)建JavaEE項目時,可能會遇到Tomcat部署的warexploded文件出現(xiàn)問題,解決方法是首先刪除有問題的warexploded依賴,然后根據圖示重新導入項目,此外,調整虛擬路徑有時也能有效解決問題2024-09-09spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解
這篇文章主要為大家介紹了spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09SpringCloud整合OpenFeign實現(xiàn)微服務間的通信
微服務之間的通信?式,通常有兩種: RPC 和 HTTP,在SpringCloud中, 默認是使?HTTP來進?微服務的通信, 最常?的實現(xiàn)形式有兩種:RestTemplate和OpenFeign,本文給大家介紹了SpringCloud整合OpenFeign實現(xiàn)微服務間的通信,需要的朋友可以參考下2024-06-06