如何搭建一個(gè)視頻網(wǎng)站互聯(lián)網(wǎng)營(yíng)銷(xiāo)專(zhuān)業(yè)
Spring Boot JpaRepository 示例
Spring Boot建立在 Spring 之上,包含 Spring 的所有功能。由于其快速的生產(chǎn)就緒環(huán)境,使開(kāi)發(fā)人員能夠直接專(zhuān)注于邏輯,而不必費(fèi)力配置和設(shè)置,因此如今它正成為開(kāi)發(fā)人員的最?lèi)?ài)。Spring Boot 是一個(gè)基于微服務(wù)的框架,在其中創(chuàng)建生產(chǎn)就緒的應(yīng)用程序只需很少的時(shí)間。以下是 Spring Boot 的一些功能:
- 它可以避免 Spring 中繁重的 XML 配置。
- 它提供了 REST 端點(diǎn)的輕松維護(hù)和創(chuàng)建。
- 它包括一個(gè)嵌入式的 Tomcat 服務(wù)器。
- 部署很簡(jiǎn)單,war和jar文件可以輕松地部署在Tomcat服務(wù)器中。
有關(guān)更多信息,請(qǐng)參閱本文:Spring Boot 簡(jiǎn)介。在本文中,我們將討論如何使用JpaRepository來(lái)管理 Spring Boot 應(yīng)用程序中的數(shù)據(jù)。
Jpa存儲(chǔ)庫(kù)
JpaRepository 是 Repository 的一個(gè)JPA(Java 持久性 API)特定擴(kuò)展。它包含CrudRepository 和 PagingAndSortingRepository的完整 API?。因此,它包含用于基本 CRUD 操作的 API 以及用于分頁(yè)和排序的 API。
句法:
public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>
這里:
- T:存儲(chǔ)庫(kù)管理的域類(lèi)型(通常是實(shí)體/模型類(lèi)名)
- ID:存儲(chǔ)庫(kù)管理的實(shí)體的 id 類(lèi)型(通常是在實(shí)體/模型類(lèi)中創(chuàng)建的 @Id 的包裝類(lèi))
插圖:
public interface DepartmentRepository extends JpaRepository<Department, Long> {}
方法
JpaRepository 中的一些最重要的方法如下
方法 1:saveAll():
保存所有給定的實(shí)體。
句法:
<S extends T> List<S> saveAll(Iterable<S> entities)
參數(shù):實(shí)體,注意它們不能為空,也不能包含空。
返回類(lèi)型:已保存的實(shí)體;永遠(yuǎn)不會(huì)為空。返回的 Iterable 將與作為參數(shù)傳遞的 Iterable 具有相同的大小。
拋出異常:如果給定的實(shí)體或其某個(gè)實(shí)體為空,則會(huì)拋出IllegalArgumentException 。
方法 2:getById():
返回具有給定標(biāo)識(shí)符的實(shí)體的引用。根據(jù) JPA 持久性提供程序的實(shí)現(xiàn)方式,這很可能始終返回一個(gè)實(shí)例并在首次訪問(wèn)時(shí)拋出 EntityNotFoundException。其中一些會(huì)立即拒絕無(wú)效標(biāo)識(shí)符。
句法:
T getById(ID id)
參數(shù):id – 不能為空。
返回類(lèi)型:對(duì)具有給定標(biāo)識(shí)符的實(shí)體的引用。
方法 3:flush():
刷新數(shù)據(jù)庫(kù)中所有待處理的更改。
句法:
void flush()
方法 4:saveAndFlush():
保存實(shí)體并立即刷新更改。
句法:
<S extends T> S saveAndFlush(S entity)
參數(shù):要保存的實(shí)體。不能為空。
返回類(lèi)型:已保存的實(shí)體
方法 5:deleteAllInBatch():
批量刪除給定實(shí)體,這意味著它將創(chuàng)建單個(gè)查詢(xún)。此類(lèi)操作會(huì)導(dǎo)致 JPA 一級(jí)緩存和數(shù)據(jù)庫(kù)不同步。在調(diào)用此方法之前,請(qǐng)考慮刷新 EntityManager。
句法:
void deleteAllInBatch(Iterable<T> entities)
參數(shù):要?jiǎng)h除的實(shí)體,不能為空。
實(shí)現(xiàn):
讓我們考慮一個(gè)使用 JpaRepository 管理 Department 實(shí)體的 Spring Boot 應(yīng)用程序。數(shù)據(jù)保存在 H2 數(shù)據(jù)庫(kù)中。我們使用 RESTful 控制器。
步驟1:使用IntelliJ IDEA創(chuàng)建Spring Boot項(xiàng)目,創(chuàng)建一個(gè)Spring Boot項(xiàng)目。
第 2 步:添加以下依賴(lài)項(xiàng)
- Spring Web
- H2 Database
- Lombok
- Spring Data JPA
示例:這是pom.xml文件的完整代碼。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
? ? ? ? ?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? ? ?xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
? ??
? ? <!-- Model version -->
? ? <modelVersion>4.0.0</modelVersion>
? ??
? ? <!-- Parent configuration for Spring Boot -->
? ? <parent>
? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? <artifactId>spring-boot-starter-parent</artifactId>
? ? ? ? <version>3.0.0</version>
? ? ? ? <relativePath/> <!-- lookup parent from repository -->
? ? </parent>
? ??
? ? <!-- Project metadata -->
? ? <groupId>com.amiya</groupId>
? ? <artifactId>Spring-Boot-Demo-Project</artifactId>
? ? <version>1.0.0-SNAPSHOT</version>
? ? <name>Spring-Boot-Demo-Project</name>
? ? <description>Demo project for Spring Boot</description>
? ??
? ? <!-- Java version property -->
? ? <properties>
? ? ? ? <java.version>17</java.version>
? ? </properties>
? ??
? ? <!-- Dependencies required for the project -->
? ? <dependencies>
? ? ? ? <!-- Spring Boot Starter Web: To build web applications -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-web</artifactId>
? ? ? ? </dependency>
? ? ? ??
? ? ? ? <!-- Spring Boot Starter Data JPA: To work with JPA for data access -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-data-jpa</artifactId>
? ? ? ? </dependency>
? ? ? ??
? ? ? ? <!-- Spring Boot Starter Validation: For Jakarta EE bean validation -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-validation</artifactId>
? ? ? ? </dependency>
? ? ? ??
? ? ? ? <!-- H2 Database: In-memory database for development and testing -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>com.h2database</groupId>
? ? ? ? ? ? <artifactId>h2</artifactId>
? ? ? ? ? ? <scope>runtime</scope>
? ? ? ? </dependency>
? ? ? ??
? ? ? ? <!-- Lombok: To reduce boilerplate code in Java classes -->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.projectlombok</groupId>
? ? ? ? ? ? <artifactId>lombok</artifactId>
? ? ? ? ? ? <optional>true</optional>
? ? ? ? </dependency>
? ? </dependencies>
? ??
? ? <!-- Build configuration -->
? ? <build>
? ? ? ? <plugins>
? ? ? ? ? ? <!-- Spring Boot Maven Plugin: To package the application as a jar/war -->
? ? ? ? ? ? <plugin>
? ? ? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ? <artifactId>spring-boot-maven-plugin</artifactId>
? ? ? ? ? ? ? ? <configuration>
? ? ? ? ? ? ? ? ? ? <excludes>
? ? ? ? ? ? ? ? ? ? ? ? <!-- Exclude Lombok from the final build -->
? ? ? ? ? ? ? ? ? ? ? ? <exclude>
? ? ? ? ? ? ? ? ? ? ? ? ? ? <groupId>org.projectlombok</groupId>
? ? ? ? ? ? ? ? ? ? ? ? ? ? <artifactId>lombok</artifactId>
? ? ? ? ? ? ? ? ? ? ? ? </exclude>
? ? ? ? ? ? ? ? ? ? </excludes>
? ? ? ? ? ? ? ? </configuration>
? ? ? ? ? ? </plugin>
? ? ? ? </plugins>
? ? </build>
</project>
步驟 3:創(chuàng)建下面列出的 4 個(gè)包,并在這些包中創(chuàng)建一些類(lèi)和接口,如下圖所示
- entity
- repository
- service
- controller
注意:
- 綠色圓形圖標(biāo)“I”按鈕是界面
- 藍(lán)色圓形圖標(biāo)“C”按鈕屬于類(lèi)
步驟 4:實(shí)體包內(nèi)部
在 Department.java 文件中創(chuàng)建一個(gè)簡(jiǎn)單的POJO 類(lèi)。
package com.amiya.springbootdemoproject.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
?* Represents a Department entity in the application.
?*/
@Entity
@Data // Generates getters, setters, toString, equals, and hashCode methods.
@NoArgsConstructor // Generates a no-args constructor.
@AllArgsConstructor // Generates a constructor with all arguments.
@Builder // Generates a builder pattern for creating instances.
public class Department {
? ? @Id // Specifies the primary key of the entity.
? ? @GeneratedValue(strategy = GenerationType.AUTO) // Auto-generates the primary key value.
? ? private Long departmentId; // Unique identifier for the department.
? ? private String departmentName; // Name of the department.
? ? private String departmentAddress; // Address of the department.
? ? private String departmentCode; // Code representing the department.
}
?
步驟 5:存儲(chǔ)庫(kù)包內(nèi)部
創(chuàng)建一個(gè)簡(jiǎn)單的接口,并將該接口命名為 DepartmentRepository。正如我們上面討論的那樣,這個(gè)接口將擴(kuò)展JpaRepository 。
例子:
// Java Program to Illustrate DepartmentRepository File
// Importing necessary packages
package com.amiya.springbootdemoproject.repository;
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
?* Repository interface for Department entity.
?* Provides CRUD operations and custom query methods through JpaRepository.
?*/
@Repository // Indicates that this interface is a Spring Data repository.
public interface DepartmentRepository extends JpaRepository<Department, Long> {}
?
步驟 6:服務(wù)包內(nèi)
在包內(nèi)創(chuàng)建一個(gè)名為DepartmentService 的接口和一個(gè)名為DepartmentServiceImpl 的類(lèi)。
示例 1-A:
// Java Program to Demonstrate DepartmentService File
// Importing required packages
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import java.util.List;
/**
?* Service interface for Department entity.
?* Defines methods for CRUD operations and additional business logic.
?*/
public interface DepartmentService {
? ? /**
? ? ?* Saves a department entity.
? ? ?* @param department the department to save
? ? ?* @return the saved department
? ? ?*/
? ? Department saveDepartment(Department department);
? ? /**
? ? ?* Fetches the list of all department entities.
? ? ?* @return a list of departments
? ? ?*/
? ? List<Department> fetchDepartmentList();
? ? /**
? ? ?* Updates an existing department entity.
? ? ?* @param department the department with updated information
? ? ?* @param departmentId the ID of the department to update
? ? ?* @return the updated department
? ? ?*/
? ? Department updateDepartment(Department department, Long departmentId);
? ? /**
? ? ?* Deletes a department entity by its ID.
? ? ?* @param departmentId the ID of the department to delete
? ? ?*/
? ? void deleteDepartmentById(Long departmentId);
}
?
示例 1-B:
// Java Program to Illustrate DepartmentServiceImpl File
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
?* Implementation of DepartmentService.
?* Provides business logic for handling department-related operations.
?*/
@Service // Marks this class as a Spring service component.
public class DepartmentServiceImpl implements DepartmentService {
? ? @Autowired
? ? private DepartmentRepository departmentRepository; // Injects the DepartmentRepository dependency.
? ? @Override
? ? public Department saveDepartment(Department department) {
? ? ? ? // Saves and returns the department entity.
? ? ? ? return departmentRepository.save(department);
? ? }
? ? @Override
? ? public List<Department> fetchDepartmentList() {
? ? ? ? // Retrieves and returns a list of all department entities.
? ? ? ? return (List<Department>) departmentRepository.findAll();
? ? }
? ? @Override
? ? public Department updateDepartment(Department department, Long departmentId) {
? ? ? ? // Finds the existing department by ID.
? ? ? ? Department depDB = departmentRepository.findById(departmentId).get();
? ? ? ??
? ? ? ? // Updates fields if they are not null or empty.
? ? ? ? if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase(department.getDepartmentName())) {
? ? ? ? ? ? depDB.setDepartmentName(department.getDepartmentName());
? ? ? ? }
? ? ? ? if (Objects.nonNull(department.getDepartmentAddress()) && !"".equalsIgnoreCase(department.getDepartmentAddress())) {
? ? ? ? ? ? depDB.setDepartmentAddress(department.getDepartmentAddress());
? ? ? ? }
? ? ? ? if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase(department.getDepartmentCode())) {
? ? ? ? ? ? depDB.setDepartmentCode(department.getDepartmentCode());
? ? ? ? }
? ? ? ??
? ? ? ? // Saves and returns the updated department entity.
? ? ? ? return departmentRepository.save(depDB);
? ? }
? ? @Override
? ? public void deleteDepartmentById(Long departmentId) {
? ? ? ? // Deletes the department entity by its ID.
? ? ? ? departmentRepository.deleteById(departmentId);
? ? }
}
?
步驟 7:控制器包裝內(nèi)部
在包內(nèi)創(chuàng)建一個(gè)名為DepartmentController 的類(lèi)。
// Java Program to Demonstrate DepartmentController File
package com.amiya.springbootdemoproject.controller;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
?* REST controller for managing Department entities.
?* Handles HTTP requests and routes them to the appropriate service methods.
?*/
@RestController // Marks this class as a RESTful controller.
public class DepartmentController {
? ? @Autowired
? ? private DepartmentService departmentService; // Injects the DepartmentService dependency.
? ? /**
? ? ?* Handles POST requests to save a new department.
? ? ?* @param department the department entity to be saved
? ? ?* @return the saved department entity
? ? ?*/
? ? @PostMapping("/departments")
? ? public Department saveDepartment(@Valid @RequestBody Department department) {
? ? ? ? return departmentService.saveDepartment(department);
? ? }
? ? /**
? ? ?* Handles GET requests to fetch the list of all departments.
? ? ?* @return a list of department entities
? ? ?*/
? ? @GetMapping("/departments")
? ? public List<Department> fetchDepartmentList() {
? ? ? ? return departmentService.fetchDepartmentList();
? ? }
? ? /**
? ? ?* Handles PUT requests to update an existing department.
? ? ?* @param department the department entity with updated information
? ? ?* @param departmentId the ID of the department to be updated
? ? ?* @return the updated department entity
? ? ?*/
? ? @PutMapping("/departments/{id}")
? ? public Department updateDepartment(@RequestBody Department department, @PathVariable("id") Long departmentId) {
? ? ? ? return departmentService.updateDepartment(department, departmentId);
? ? }
? ? /**
? ? ?* Handles DELETE requests to remove a department by ID.
? ? ?* @param departmentId the ID of the department to be deleted
? ? ?* @return a success message
? ? ?*/
? ? @DeleteMapping("/departments/{id}")
? ? public String deleteDepartmentById(@PathVariable("id") Long departmentId) {
? ? ? ? departmentService.deleteDepartmentById(departmentId);
? ? ? ? return "Deleted Successfully";
? ? }
}
?
步驟 8:下面是 application.properties 文件的代碼
server.port=8082# H2 Database spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:dcbapp spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
現(xiàn)在運(yùn)行您的應(yīng)用程序,讓我們?cè)?Postman 中測(cè)試端點(diǎn)并參考我們的 H2 數(shù)據(jù)庫(kù)。
在 Postman 中測(cè)試端點(diǎn)
端點(diǎn) 1:?POST – http://localhost:8082/departments/
端點(diǎn) 2:?GET – http://localhost:8082/departments/
端點(diǎn) 3:?PUT – http://localhost:8082/departments/1
端點(diǎn) 4:刪除 – http://localhost:8082/departments/1
H2數(shù)據(jù)庫(kù)如下: