Spring Boot H2 简明教程

Spring Boot & H2 - Quick Guide

Spring Boot & H2 - Overview

What is H2?

H2 数据库是一个开源、嵌入式且内存驻留的关系数据库管理系统。它使用 Java 编写,提供一个客户端/服务器应用程序。它将数据存储在系统内存中,而不是磁盘。一旦程序关闭,数据也会丢失。当我们不想保留数据以及单元测试整体功能时,可以使用内存数据库。其他一些流行的内存数据库包括 HSQLDB 或 HyperSQL 数据库以及 Apache Derby。H2 是其他嵌入式数据库中最流行的数据库。

H2 database is an open source, embedded and in memory relational database management system. It is written in Java and provides a client/server application. It stores data in system memory instead of disk. Once program is closed, data is also lost. An in memory database is used when we don’t want to persist the data and unit test the overall functionality. Some of the other popular in memory databases are HSQLDB or HyperSQL Database and Apache Derby. H2 is the most popular one among other embedded databases.

Advantages of H2 Database

以下是 H2 提供的优势列表 -

Following is the list of advantages that H2 provides −

  1. No configuration − Spring Boot intrinsically supports H2 and no extra configuration required to configure H2 database.

  2. Easy to Use − H2 Database is very easy to use.

  3. Lightweight and Fast − H2 database is very lightweight and being in memory, it is very fast.

  4. Switch configurations − Using profiles, you can easily switch between production level database and in-memory database.

  5. Supports Standard SQL and JDBC − H2 database supports almost all the features of Standard SQL and operations of JDBC.

  6. Web Based Console − H2 Database can be managed by its web based console application.

Configuring H2 Database

将 H2 数据库添加为 maven 依赖项,就是这样。

Add H2 Database as maven dependency and that’s it.

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>

尽管 Spring Boot 会自动配置 H2 数据库。我们可以在 application.properties 中指定它们来覆盖默认配置,如下所示。

Although, spring boot configures H2 database automatically. We can override the default configurations by specifying them in application.properties as shown below.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

Persisting H2 Data

如果需要持久性存储,则在 application.properties 中添加以下配置。

If persistent storage is needed than add the following configuration in application.properties.

spring.datasource.url=jdbc:h2:file:/data/database
spring.datasource.url=jdbc:h2:C:/data/database

Spring Boot & H2 - Environment Setup

本章将指导你如何准备一个开发环境来开始你使用 Spring Framework 的工作。它还将教你如何在设置 Spring Framework 之前在你的机器上设置 JDK、Tomcat 和 Eclipse −

This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework −

Step 1 - Setup Java Development Kit (JDK)

Java SE 可免费下载。若要下载 click here,请下载与你的操作系统兼容的版本。

Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

按照说明下载 Java,并运行 .exe 在你的计算机上安装 Java。在计算机上安装 Java 后,你需要设置环境变量来指向正确的安装目录。

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中 −

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  1. Right-click on 'My Computer' and select 'Properties'.

  2. Click on the 'Environment variables' button under the 'Advanced' tab.

  3. Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way

C:\Windows\System32;c:\Program Files\java\jdk\bin

Setting Up the Path for Windows 95/98/ME

假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中 −

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  1. Edit the 'C:\autoexec.bat' file and add the following line at the end −

SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

环境变量 PATH 应设置为指向已安装 Java 二进制文件的位置。如果你在这方面遇到问题,请参阅 shell 文档。

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

例如,如果你使用 bash 作为你的 shell,那么你将在 .bashrc 的末尾添加以下行 −

For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc

export PATH=/path/to/java:$PATH'

或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Step 2 - Setup Eclipse IDE

本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。

All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.

要安装 Eclipse IDE,请从 www.eclipse.org/downloads 下载最新的 Eclipse 二进制文件。下载安装文件后,将二进制分发包解压到方便的位置。例如,在 Windows 上的 C:\eclipse 中,或 Linux/Unix 上的 /usr/local/eclipse 中,最后相应地设置 PATH 变量。

To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.

可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe

Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe

%C:\eclipse\eclipse.exe

可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −

Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −

$/usr/local/eclipse/eclipse

Step 3 - Setup m2eclipse

M2Eclipse 是一个 Eclipse 插件,它对于将 Apache Maven 集成到 Eclipse IDE 中非常有用。我们在本教程中使用 maven 来构建 spring boot 项目,并使用 m2eclipse 在 eclipse 内运行示例。

M2Eclipse is eclipse plugin which is very useful integration for Apache Maven into the Eclipse IDE. We are using maven in this tutorial to build spring boot project and examples are run within eclipse using m2eclipse.

使用 Eclipse IDE 中的 Install New Software 对话框安装最新的 M2Eclipse 版本,并将其指向这个 p2 存储库: https://download.eclipse.org/technology/m2e/releases/latest/

Install the latest M2Eclipse release by using the Install New Software dialog in Eclipse IDE, and point it to this p2 repository: https://download.eclipse.org/technology/m2e/releases/latest/

Step 4 - Setup Spring Boot Project

现在,如果一切正常,则可以继续设置 Spring Boot。以下是下载和在机器上安装 Spring Boot 项目的简单步骤。

Now if everything is fine, then you can proceed to set up your Spring Boot. Following are the simple steps to download and install the Spring Boot Project on your machine.

  1. Go to spring Initializr link to create a spring boot project, https://start.spring.io/.

  2. Select project as Maven Project.

  3. Select language as Java.

  4. Select Spring Boot version as 2.5.3.

  5. Set Project Metadata - Group as com.tutorialspoint, Artifact as springboot-h2, name as springboot-h2, Description as Demo project for Spring Boot and H2 Database and package name as com.tutorialspoint.springboot-h2.

  6. Select packaging as Jar.

  7. Select java as 11.

  8. Add dependencies as Spring Web, Spring Data JPA, H2 Database and Spring Boot DevTools.

现在点击生成按钮来生成项目结构。

Now click on GENERATE Button to generate the project structure.

spring initializr

一旦基于 maven 的 Spring Boot 项目下载完成,然后将 maven 项目导入 eclipse,其余操作由 eclipse 处理。它将下载 maven 依赖关系,并构建项目以使之可以进行进一步的开发。

Once the maven based spring boot project is downloaded, then import the maven project into eclipse and rest eclipse will handle. It will download the maven dependencies and build the project to make it ready for further development.

Step 5 - POSTMAN for REST APIs Testing

POSTMAN 是一款用来测试基于 REST 的 API 的有用工具。要安装 POSTMAN,可从 www.postman.com/downloads/ 下载最新的 POSTMAN 二进制文件。下载完可安装文件后,按照说明进行安装并使用。

POSTMAN is a useful tool to test REST Based APIs. To install POSTMAN, download the latest POSTMAN binaries from www.postman.com/downloads/. Once you download the installable, follow the instructions to install and use it.

Spring Boot & H2 - Project Setup

如前一章 Environment Setup 中所述,我们在 Eclipse 中导入了 Spring Boot 生成的项目。现在让我们在 src/main/java 文件夹中创建以下结构。

As in previous chapter Environment Setup, we’ve imported the generated spring boot project in eclipse. Now let’s create the following structure in src/main/java folder.

project structure
  1. com.tutorialspoint.controller.EmployeeController − A REST Based Controller to implement REST based APIs.

  2. com.tutorialspoint.entity.Employee − An entity class representing the corresponding table in database.

  3. com.tutorialspoint.repository.EmployeeRepository − A Repository Interface to implement the CRUD operations on the database.

  4. com.tutorialspoint.service.EmployeeService − A Service Class to implement the business opearations over repository functions.

  5. com.tutorialspoint.springbooth2.SprintBootH2Application − A Spring Boot Application class.

SprintBootH2Application类已存在。我们须创建上述包和相关类和接口如下所示——

SprintBootH2Application class is already present. We need to create the above packages and relevant classes and interface as shown below −

Entity - Entity.java

以下为Employee的默认代码。它表示一个带id,name,age和email列的Employee表。

Following is the default code of Employee. It represents a Employee table with id, name, age and email columns.

package com.tutorialspoint.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Employee {
   @Id
   @Column
   private int id;
   @Column
   private String name;
   @Column
   private int age;
   @Column
   private String email;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email = email;
   }
}

Repository - EmployeeRepository.java

以下为实现上述实体创建CRUD操作的存储库的默认代码,Employee。

Following is the default code of Repository to implement CRUD operations on above entity, Employee.

package com.tutorialspoint.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tutorialspoint.entity.Employee;
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>  {
}

Service - EmployeeService.java

以下为实现库函数操作的服务的默认代码。

Following is the default code of Service to implement operations over repository functions.

package com.tutorialspoint.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;
@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;
   public Employee getEmployeeById(int id) {
      return null;
   }
   public List<Employee> getAllEmployees(){
      return null;
   }
   public void saveOrUpdate(Employee employee) {
   }
   public void deleteEmployeeById(int id) {
   }
}

Controller - EmployeeController.java

以下为实现REST API的控制器的默认代码。

Following is the default code of Controller to implement REST APIs.

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return null;
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return null;;
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
   }
}

Application - SprintBootH2Application.java

以下为用于使用上述类的Application的更新代码。

Following is the updated code of Application to use above classes.

package com.tutorialspoint.sprintbooth2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ComponentScan({"com.tutorialspoint.controller","com.tutorialspoint.service"})
@EntityScan("com.tutorialspoint.entity")
@EnableJpaRepositories("com.tutorialspoint.repository")
@SpringBootApplication
public class SprintBootH2Application {
   public static void main(String[] args) {
      SpringApplication.run(SprintBootH2Application.class, args);
   }
}

Run/Debug Configuration

在eclipse中创建以下 maven configuration 来运行带目标 spring-boot:run 的springboot应用程序。此配置将有助于运行REST API,我们可以使用POSTMAN对其进行测试。

Create following maven configuration in eclipse to run the springboot application with goal spring-boot:run. This configuration will help to run the REST APIs and we can test them using POSTMAN.

maven configuration

Spring Boot & H2 - REST APIs

与上一章 Application Setup 一样,我们在 Spring Boot 项目中创建了所需文件。现在在 POSTMAN 中创建以下集合来测试 REST API。

As in previous chapter Application Setup, we’ve created the required files in spring boot project. Now create the following collection in POSTMAN to test the REST APIs.

postman structure
  1. GET Get All Employees − A GET request to return all the employees.

  2. POST Add an Employee − A POST request to create an employee.

  3. PUT Update an Employee − A PUT request to update an existing employee.

  4. GET An Employee − A GET request to get an employee identified by its id.

  5. Delete An Employee − A Delete request to delete an employee identified by its id.

GET All Employees

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL − http://localhost:8080/emp/employees

Add an Employee

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

Update an Employee

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − PUT

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie.roberts@gmail.com"
}

GET An Employees

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL - http://localhost:8080/emp/employee/1 − Where 1 is the employee id

Delete An Employees

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − DELETE

  2. URL - http://localhost:8080/emp/employee/1 − Where 1 is the employee id

Spring Boot & H2 - Console

与上一章 Application Setup 一样,我们在 Spring Boot 项目中创建了所需文件。现在让我们来更新位于 src/main/resourcespom.xml 中的 application.properties,以使用 maven-resources-plugin 的不同版本。

As in previous chapter Application Setup, we’ve created the required files in spring boot project. Now let’s update the application.properties lying in src/main/resources and pom.xml to use a different version of maven-resources-plugin.

application.properties

spring.datasource.url=jdbc:h2:mem:testdb

pom.xml

...
<build>
   <plugins>
      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-resources-plugin</artifactId>
         <version>3.1.0</version>
      </plugin>
   </plugins>
</build>
...

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< com.tutorialspoint:sprint-boot-h2 >------------------
[INFO] Building sprint-boot-h2 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
...
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.2)

...
2021-07-24 20:51:11.347  INFO 9760 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat initialized with port(s): 8080 (http)
...
2021-07-24 20:51:11.840  INFO 9760 --- [  restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration
: H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
...
2021-07-24 20:51:14.805  INFO 9760 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer
: Tomcat started on port(s): 8080 (http) with context path ''
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,在浏览器中打开 localhost:8080/h2-console ,然后点击“测试连接”以验证数据库连接。

Once server is up and running, open localhost:8080/h2-console in a browser and click on Test Connection to verify the database connection.

h2 console login

点击“连接”按钮,H2 数据库窗口将如以下所示出现 -

Click on Connect button and H2 database window will appear as shown below −

h2 console

Spring Boot & H2 - Add Record

让我们现在更新到目前创建的项目,以准备一个完整的添加记录 API 并对其进行测试。

Let’s now update the project created so far to prepare a complete Add Record API and test it.

Update Service

// Use repository.save() to persist Employee entity in database
public void saveOrUpdate(Employee employee) {
   repository.save(employee);
}

EmployeeService

package com.tutorialspoint.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;
@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;
   public Employee getEmployeeById(int id) {
      return null;
   }
   public List<Employee> getAllEmployees(){
      return null;
   }
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   public void deleteEmployeeById(int id) {
   }
}

Update Controller

// Use service.saveOrUpdate() to persist Employee entity in database
@PostMapping("/employee")
public void addEmployee(@RequestBody Employee employee) {
   employeeService.saveOrUpdate(employee);
}

EmployeeController

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return null;
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return null;;
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
   }
}

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 执行 POST 请求 -

Once server is up and running, Use Postman to make a POST request −

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

单击发送按钮并检查响应状态是否为 OK。现在打开 H2 控制台并使用以下查询验证已插入的记录 -

Click on Send Button and check the response status to be OK. Now open H2-Console and verify the inserted record using following query −

Select * from Employee;

它应显示以下结果 -

It should display following result −

ID    AGE    EMAIL              NAME
1     35   julie@gmail.com      Julie

Spring Boot & H2 - Get Record

现在让我们来更新到目前为止创建的项目,以准备一个完整的获取记录 API 并对其进行测试。

Let’s now update the project created so far to prepare a complete Get Record API and test it.

Update Service

// Use repository.findById() to get Employee entity by Id
public Employee getEmployeeById(int id) {
   return repository.findById(id).get();
}

EmployeeService

package com.tutorialspoint.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;
@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;
   public Employee getEmployeeById(int id) {
      return repository.findById(id).get();
   }
   public List<Employee> getAllEmployees(){
      return null;
   }
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   public void deleteEmployeeById(int id) {
   }
}

Update Controller

// Use service.getEmployeeById() to get Employee entity from database
@GetMapping("/employee/{id}")
public Employee getEmployee(@PathVariable("id") int id) {
   return employeeService.getEmployeeById(id);
}

EmployeeController

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return null;
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
   }
}

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。

Once server is up and running, Use Postman to make a POST request to add a record first.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

点击发送按钮并检查响应状态是否为 OK。现在发送一个 GET 请求来获取该记录。

Click on Send Button and check the response status to be OK. Now make a GET Request to get that record.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL − http://localhost:8080/emp/employee/1

单击发送按钮并验证响应。

Click the send button and verify the response.

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

Spring Boot & H2 - Get All Records

让我们现在更新到目前创建的项目,以准备一个完整的所有记录获取 API 并对其进行测试。

Let’s now update the project created so far to prepare a complete Get All Records API and test it.

Update Service

// Use repository.findAll() to get all Employee records
public List<Employee> getAllEmployees(){
   List<Employee> employees = new ArrayList<Employee>();
   repository.findAll().forEach(employee -> employees.add(employee));
   return employees;
}

EmployeeService

package com.tutorialspoint.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;
@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;
   public Employee getEmployeeById(int id) {
      return repository.findById(id).get();
   }
   public List<Employee> getAllEmployees(){
      List<Employee> employees = new ArrayList<Employee>();
      repository.findAll().forEach(employee -> employees.add(employee));
      return employees;
   }
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   public void deleteEmployeeById(int id) {
   }
}

Update Controller

// Use service.getAllEmployees() to get a list of employees from database
@GetMapping("/employees")
public List<Employee> getAllEmployees(){
   return employeeService.getAllEmployees();
}

EmployeeController

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return employeeService.getAllEmployees();
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
   }
}

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。

Once server is up and running, Use Postman to make a POST request to add a record first.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

单击发送按钮并检查响应状态是否为 OK。现在执行 GET 请求以获取所有记录。

Click on Send Button and check the response status to be OK. Now make a GET Request to get all records.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL − http://localhost:8080/emp/employees

单击发送按钮并验证响应。

Click the send button and verify the response.

[{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}]

Spring Boot & H2 - Update Record

让我们现在更新到目前为止创建的项目以准备一个完整的更新记录API并对其进行测试。

Let’s now update the project created so far to prepare a complete Update Record API and test it.

Update Controller

// Use service.saveOrUpdate() to update an employee record
@PutMapping("/employee")
public void updateEmployee(@RequestBody Employee employee) {
   employeeService.saveOrUpdate(employee);
}

EmployeeController

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return employeeService.getAllEmployees();
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
      employeeService.deleteEmployeeById(id);
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
}

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。

Once server is up and running, Use Postman to make a POST request to add a record first.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

单击发送按钮并检查响应状态是否为OK。

Click on Send Button and check the response status to be OK.

现在发出Put请求来更新该记录。

Now make a Put Request to update that records.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − PUT

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie.roberts@gmail.com"
}

单击发送按钮并验证响应状态是否为OK。

Click the send button and verify the response status to be OK.

现在发出GET请求来获取所有记录。

Now make a GET Request to get all records.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL − http://localhost:8080/emp/employees

单击发送按钮并验证响应。

Click the send button and verify the response.

[{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie.roberts@gmail.com"
}]

Spring Boot & H2 - Delete Record

现在,让我们更新到目前为止创建的项目,以准备一个完整的 Delete Record API 并对其进行测试。

Let’s now update the project created so far to prepare a complete Delete Record API and test it.

Update Service

// Use repository.deleteById() to delete an Employee record
public void deleteEmployeeById(int id) {
   repository.deleteById(id);
}

EmployeeService

package com.tutorialspoint.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;
@Service
public class EmployeeService {
   @Autowired
   EmployeeRepository repository;
   public Employee getEmployeeById(int id) {
      return repository.findById(id).get();
   }
   public List<Employee> getAllEmployees(){
      List<Employee> employees = new ArrayList<Employee>();
      repository.findAll().forEach(employee -> employees.add(employee));
      return employees;
   }
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   public void deleteEmployeeById(int id) {
      repository.deleteById(id);
   }
}

Update Controller

// Use service.deleteEmployeeById() to delete an employee by id
@DeleteMapping("/employee/{id}")
public void deleteEmployee(@PathVariable("id") int id) {
   employeeService.deleteEmployeeById(id);
}

EmployeeController

package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
   @Autowired
   EmployeeService employeeService;
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return employeeService.getAllEmployees();
   }
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
      employeeService.deleteEmployeeById(id);
   }
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
   }
}

Run the application

在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。

In eclipse, run the Employee Application configuration as prepared during Application Setup

Eclipse 控制台将显示类似的输出。

Eclipse console will show the similar output.

[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823  INFO 9760 --- [  restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)

服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。

Once server is up and running, Use Postman to make a POST request to add a record first.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − POST

  2. URL − http://localhost:8080/emp/employee

  3. BODY − An employee JSON

{
   "id": "1",
   "age": "35",
   "name": "Julie",
   "email": "julie@gmail.com"
}

单击发送按钮并检查响应状态是否为OK。

Click on Send Button and check the response status to be OK.

现在发送一个 Delete 请求以删除该记录。

Now make a Delete Request to delete that records.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − DELETE

  2. URL − http://localhost:8080/emp/employee/1

单击发送按钮并验证响应状态是否为OK。

Click the send button and verify the response status to be OK.

现在发出GET请求来获取所有记录。

Now make a GET Request to get all records.

在 POSTMAN 中设置以下参数。

Set the following parameters in POSTMAN.

  1. HTTP Method − GET

  2. URL − http://localhost:8080/emp/employees

单击发送按钮并验证响应。

Click the send button and verify the response.

[]

Spring Boot & H2 - Unit Test Controller

与前一章一样,我们已经完成了 REST API。现在,让我们在 src/main/test 文件夹中创建以下结构。

As in previous chapter we’ve completed our REST APIs. Now let’s create the following structure in src/main/test folder.

test structure
  1. com.tutorialspoint.controller.EmployeeControllerTest − A Unit Tester Class to unit test all methods of EmployeeController.

  2. com.tutorialspoint.repository.EmployeeRepositoryTest − A Unit Tester Class to unit test all methods of EmployeeRepository.

  3. com.tutorialspoint.service.EmployeeServiceTest − A Unit Tester Class to unit test all methods of EmployeeService.

SprintBootH2ApplicationTests 类已存在。我们需要创建上述包和相关类。

SprintBootH2ApplicationTests class is already present. We need to create the above packages and relevant classes.

EmployeeControllerTest

要测试 REST 控制器,我们需要以下注释和类:

To test a REST Controller, we need the following annotation and classes −

  1. @ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.

  2. @SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.

  3. @AutoConfigureMockMvc − To automatically configure the MockMVC to mock HTTP Requests and Response.

  4. @Autowired private MockMvc mvc; − MockMvc object to be used in testing.

  5. @MockBean private EmployeeController employeeController − EmployeeController mock object to be tested.

以下是 EmployeeControllerTest 的完整代码。

Following is the complete code of EmployeeControllerTest.

package com.tutorialspoint.controller;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.sprintbooth2.SprintBootH2Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SprintBootH2Application.class)
@AutoConfigureMockMvc
public class EmployeeControllerTest {
   @Autowired
   private MockMvc mvc;
   @MockBean
   private EmployeeController employeeController;
   @Test
   public void testGetAllEmployees() throws Exception {
      Employee employee = getEmployee();
      List<Employee> employees = new ArrayList<>();
      employees.add(employee);
      given(employeeController.getAllEmployees()).willReturn(employees);
      mvc.perform(get("/emp/employees/").contentType(APPLICATION_JSON)).andExpect(status().isOk())
         .andExpect(jsonPath("$[0].name", is(employee.getName())));
   }
   @Test
   public void testGetEmployee() throws Exception {
      Employee employee = getEmployee();
      given(employeeController.getEmployee(1)).willReturn(employee);
      mvc.perform(get("/emp/employee/" + employee.getId()).contentType(APPLICATION_JSON)).andExpect(status().isOk())
         .andExpect(jsonPath("name", is(employee.getName())));
   }
   @Test
   public void testDeleteEmployee() throws Exception {
      Employee employee = getEmployee();
      doNothing().when(employeeController).deleteEmployee(1);
      mvc.perform(delete("/emp/employee/" + employee.getId()).contentType(APPLICATION_JSON))
         .andExpect(status().isOk()).andReturn();
   }
   @Test
   public void testAddEmployee() throws Exception {
      Employee employee = getEmployee();
      doNothing().when(employeeController).addEmployee(employee);
      mvc.perform(post("/emp/employee/").content(asJson(employee)).contentType(APPLICATION_JSON))
         .andExpect(status().isOk()).andReturn();
   }
   @Test
   public void testUpdateEmployee() throws Exception {
      Employee employee = getEmployee();
      doNothing().when(employeeController).updateEmployee(employee);
      mvc.perform(put("/emp/employee/").content(asJson(employee)).contentType(APPLICATION_JSON))
         .andExpect(status().isOk()).andReturn();
   }
   private Employee getEmployee() {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setAge(30);
      employee.setEmail("mahesh@test.com");
      return employee;
   }
   private static String asJson(final Object obj) {
      try {
         return new ObjectMapper().writeValueAsString(obj);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }
}

Run the test cases.

在 Eclipse 中右键单击该文件并选择 Run a JUnit Test ,然后验证结果。

Right Click on the file in eclipse and select Run a JUnit Test and verify the result.

controller test result

Spring Boot & H2 - Unit Test Service

要测试服务,我们需要以下注释和类——

To test a Service, we need the following annotation and classes −

  1. @ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.

  2. @SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.

  3. @MockBean private EmployeeService employeeService − EmployeeService mock object to be tested.

以下是 EmployeeServiceTest 的完整代码。

Following is the complete code of EmployeeServiceTest.

package com.tutorialspoint.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.sprintbooth2.SprintBootH2Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SprintBootH2Application.class)
public class EmployeeServiceTest {
   @MockBean
   private EmployeeService employeeService;
   @Test
   public void testGetAllEmployees() throws Exception {
      Employee employee = getEmployee();
      List<Employee> employees = new ArrayList<>();
      employees.add(employee);
      given(employeeService.getAllEmployees()).willReturn(employees);
      List<Employee> result = employeeService.getAllEmployees();
      assertEquals(result.size(), 1);
   }
   @Test
   public void testGetEmployee() throws Exception {
      Employee employee = getEmployee();
      given(employeeService.getEmployeeById(1)).willReturn(employee);
      Employee result = employeeService.getEmployeeById(1);
      assertEquals(result.getId(), 1);
   }
   @Test
   public void testDeleteEmployee() throws Exception {
      doNothing().when(employeeService).deleteEmployeeById(1);
      employeeService.deleteEmployeeById(1);
      assertTrue(true);
   }
   @Test
   public void testSaveOrUpdateEmployee() throws Exception {
      Employee employee = getEmployee();
      doNothing().when(employeeService).saveOrUpdate(employee);
      employeeService.saveOrUpdate(employee);
      assertTrue(true);
   }
   private Employee getEmployee() {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setAge(30);
      employee.setEmail("mahesh@test.com");
      return employee;
   }
}

Run the test cases.

在 Eclipse 中右键单击该文件并选择 Run a JUnit Test ,然后验证结果。

Right Click on the file in eclipse and select Run a JUnit Test and verify the result.

service test result

Spring Boot & H2 - Unit Test Repository

要测试存储库,我们需要以下注释和类:

To test a Repository, we need the following annotation and classes −

  1. @ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.

  2. @SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.

  3. @Transactional − To mark repository to do CRUD Operation capable.

  4. @Autowired private EmployeeRepository employeeRepository − EmployeeRepository object to be tested.

以下是 EmployeeRepositoryTest 的完整代码。

Following is the complete code of EmployeeRepositoryTest.

package com.tutorialspoint.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.sprintbooth2.SprintBootH2Application;
@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest(classes = SprintBootH2Application.class)
public class EmployeeRepositoryTest {
   @Autowired
   private EmployeeRepository employeeRepository;
   @Test
   public void testFindById() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      Employee result = employeeRepository.findById(employee.getId()).get();
      assertEquals(employee.getId(), result.getId());
   }
   @Test
   public void testFindAll() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      List<Employee> result = new ArrayList<>();
      employeeRepository.findAll().forEach(e -> result.add(e));
      assertEquals(result.size(), 1);
   }
   @Test
   public void testSave() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      Employee found = employeeRepository.findById(employee.getId()).get();
      assertEquals(employee.getId(), found.getId());
   }
   @Test
   public void testDeleteById() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      employeeRepository.deleteById(employee.getId());
      List<Employee> result = new ArrayList<>();
      employeeRepository.findAll().forEach(e -> result.add(e));
      assertEquals(result.size(), 0);
   }
   private Employee getEmployee() {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setAge(30);
      employee.setEmail("mahesh@test.com");
      return employee;
   }
}

Run the test cases.

在 Eclipse 中右键单击该文件并选择 Run a JUnit Test ,然后验证结果。

Right Click on the file in eclipse and select Run a JUnit Test and verify the result.

repository test result