Spring Boot H2 数据库REST API示例

Spring Boot H2 Database - javatpointicon-default.png?t=M0H8https://www.javatpoint.com/spring-boot-h2-database

什么是内存数据库

内存数据库依赖于系统内存,而不是磁盘空间来存储数据。因为内存访问比磁盘访问更快。当我们不需要持久保存数据时,我们使用内存数据库。内存数据库是一个嵌入式数据库。默认情况下,内存中的数据库是易失性的,并且当我们重新启动应用程序时,所有存储的数据都会丢失。

广泛使用的内存数据库是H2、HSQLDB(HyperSQL 数据库)Apache Derby。它会自动创建配置。

持久性与内存数据库

持久数据库将数据持久保存在物理内存中。即使数据库服务器被退回,数据仍然可用。一些流行的持久性数据库是Oracle

MySQL

Postgres

, etc.

在内存数据库的情况下,数据存储在系统内存中。当程序关闭时,它会丢失数据。它有助于POC(概念证明),而不是生产应用程序。广泛使用的内存数据库是H2。

21.2M
400
Prime Ministers of India | List of Prime Minister of India (1947-2020)

什么是 H2 数据库

H2是一个嵌入式、开源内存数据库。它是一个用Java

编写的关系数据库管理系统。它是一个客户端/服务器应用程序。它通常用于单元测试。它将数据存储在内存中,而不是将数据持久存储在磁盘上。

好处

  • 零配置
  • 这个用起来很简单。
  • 它重量轻,速度快。
  • 它提供了简单的配置来在真实数据库和内存数据库之间切换。
  • 它支持标准的 SQL 和 JDBC API。
  • 它提供了一个 Web 控制台以在数据库中进行维护。

配置 H2 数据库

如果我们想在应用程序中使用 H2 数据库,我们需要在 pom.xml 文件中添加以下依赖项:

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

添加依赖后,我们需要配置H2数据库的数据源URL、驱动类名、用户名密码。Spring Boot 提供了一种在application.properties文件中配置这些属性的简单方法。

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.datasource.url属性中,mem是内存数据库的名称,testdb是 H2 提供的模式的名称,默认情况下。我们还可以定义自己的模式和数据库。默认用户名是sa,空密码表示密码。如果我们想更改用户名和密码,我们可以覆盖这些值。

持久化 H2 数据库中的数据

如果我们想将数据持久化到 H2 数据库中,我们应该将数据存储在一个文件中。为此,我们需要更改数据源URL

属性。

#persist the data
#spring.datasource.url=jdbc:h2:file:/data/sampledata
#spring.datasource.url=jdbc:h2:C:/data/sampledata

在上述属性中,sampledata是一个文件名。

创建架构并填充数据

我们可以通过在资源文件夹(src/main/resource)中创建一个SQL

文件来定义模式。

schema.sql

DROP TABLE IF EXISTS CITY;  
CREATE TABLE CITY (  
City_code INT AUTO_INCREMENT  PRIMARY KEY,  
city_name VARCHAR(50) NOT NULL,  
city_pincode INT(8) NOT NULL  
);  

我们可以通过在资源文件夹(src/main/resource)中创建一个SQL文件来填充表中的数据。

data.sql

INSERT INTO CITY VALUES (11, 'Delhi', 110001);    
INSERT INTO CITY VALUES (12, 'Kanpur', 208001);    
INSERT INTO CITY VALUES (13, 'Lucknow', 226001);    

Spring Boot 在应用程序启动期间自动获取data.sql文件并针对 H2 数据库运行它。

H2 控制台

默认情况下,H2 数据库的控制台视图是禁用的。在访问 H2 数据库之前,我们必须使用以下属性启用它。

#enabling the H2 console  
spring.h2.console.enabled=true  

一旦我们启用了 H2 控制台,现在我们可以通过调用 URL http://localhost:8080/h2-console 在浏览器中访问 H2 控制台。下图为H2数据库的控制台视图。

在上面的屏幕截图中,我们定义了自己的名为javatpoint的数据库。

Spring Boot H2 示例

让我们使用 H2 数据库设置一个 Spring Boot 应用程序。

第 1 步:打开 Spring Initializr http://start.spring.io

第 2 步:选择Spring Boot 2.3.0.M1版本

第 3 步:提供名称。我们提供了com.javatpoint。

第 4 步:提供工件ID。我们提供了spring-boot-h2-database-example。

第 5 步:添加的依赖关系的Spring Web,春数据JPA

H2数据库。

第 6 步:单击“生成”按钮。当我们单击 Generate 按钮时,它会将项目包装在一个Jar文件中并将其下载到本地系统。

第 7 步: 提取Jar 文件并将其粘贴到 STS 工作区。

第8步: 导入项目文件夹为STS。

文件 -> 导入 -> 现有 Maven 项目 -> 浏览 -> 选择文件夹 spring-boot-h2-database-example -> 完成

导入需要一些时间。

步骤 9:在文件夹src/main/java 中创建一个名为com.javatpoint.model的包

第 10 步:在包com.javatpoint.model 中创建模型类我们创建了名为Student 的模型类在 Books 类中,我们做了以下工作:

  • 定义四个变量id、age、name
  • 生成 Getter 和 Setter。
    右键单击文件 -> 源 -> 生成 Getter 和 Setter。
  • 使用注解@Entity将类标记为实体
  • 使用注解@Table将类标记为
  • 使用注释@Column将每个变量定义为Column 

Student.java

package com.javatpoint.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

//mark class as an Entity 
@Entity
//defining class name as Table name
@Table
public class Student {
//mark id as primary key
	@Id
//defining id as column name
	@Column
	private int id;
//defining name as column name
	@Column
	private String name;
//defining age as column name
	@Column
	private int age;
//defining email as column name
	@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;
	}
}

第 11 步:在文件夹src/main/java 中创建一个名为com.javatpoint.controller的包

第 12 步:在包com.javatpoint.controller 中创建一个 Controller 类。我们创建了名为StudentController 的控制器类。在 StudentController 类中,我们做了以下事情:

  • 将类标记为RestController通过使用注释@RestController。
  • 自动装配的StudentService通过使用注释类@Autowired
  • 定义以下方法:
    • getAllStudent():它返回所有学生的列表。
    • getStudent():它返回我们在路径变量中指定的学生详细信息。我们使用注解@PathVariable 将id 作为参数传递。注释表明方法参数应绑定到 URI 模板变量。
    • deleteStudent():它删除我们在路径变量中指定的特定学生。
    • saveStudent():保存学生详细信息。注解 @RequestBody 表示方法参数应该绑定到 Web 请求的正文。

StudentController.java

package com.javatpoint.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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.javatpoint.model.Student;
import com.javatpoint.service.StudentService;

//creating RestController
@RestController
public class StudentController {
//autowired the StudentService class
	@Autowired
	StudentService studentService;

//creating a get mapping that retrieves all the students detail from the database 
	@GetMapping("/student")
	private List<Student> getAllStudent() {
		return studentService.getAllStudent();
	}

//creating a get mapping that retrieves the detail of a specific student
	@GetMapping("/student/{id}")
	private Student getStudent(@PathVariable("id") int id) {
		return studentService.getStudentById(id);
	}

//creating a delete mapping that deletes a specific student
	@DeleteMapping("/student/{id}")
	private void deleteStudent(@PathVariable("id") int id) {
		studentService.delete(id);
	}

//creating post mapping that post the student detail in the database
	@PostMapping("/student")
	private int saveStudent(@RequestBody Student student) {
		studentService.saveOrUpdate(student);
		return student.getId();
	}
}

第 13 步:在文件夹src/main/java 中创建一个名为com.javatpoint.service的包

第 14 步:创建一个服务类。我们创建了一个服务类的名称StudentService在包com.javatpoint.service。

StudentService.java

package com.javatpoint.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javatpoint.model.Student;
import com.javatpoint.repository.StudentRepository;

//defining the business logic
@Service
public class StudentService {
	@Autowired
	StudentRepository studentRepository;

//getting all student records
	public List<Student> getAllStudent() {
		List<Student> students = new ArrayList<Student>();
		studentRepository.findAll().forEach(student -> students.add(student));
		return students;
	}

//getting a specific record
	public Student getStudentById(int id) {
		return studentRepository.findById(id).get();
	}

	public void saveOrUpdate(Student student) {
		studentRepository.save(student);
	}

//deleting a specific record
	public void delete(int id) {
		studentRepository.deleteById(id);
	}
}

第 15 步:在文件夹src/main/java中创建一个名为com.javatpoint.repository的包。

第 16 步:创建存储库接口。我们在com.javatpoint.repository包中创建了一个名为StudentRepository的存储库接口它扩展了Crud Repository接口。

StudentRepository.java

package com.javatpoint.repository;

import org.springframework.data.repository.CrudRepository;
import com.javatpoint.model.Student;

public interface StudentRepository extends CrudRepository<Student, Integer> {
}

现在我们将在application.properties文件中配置数据源URL、驱动程序类名称、用户名密码。

第 17 步:打开application.properties文件并配置以下属性。

application.properties

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

注意:不要忘记启用 H2 控制台。

创建所有类和包后,项目目录如下所示。

现在我们将运行应用程序。

第 18 步:打开SpringBootH2DatabaseExampleApplication.java文件并将其作为 Java 应用程序运行。

SpringBootH2DatabaseExampleApplication.java

package com.javatpoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootH2DatabaseExampleApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringBootH2DatabaseExampleApplication.class, args);
	}
}

在下一步中,我们将使用 REST 客户端Postman来发送POSTGET请求如果您的系统中没有安装 Postman,请按照以下步骤操作:

第 19 步:打开Postman并执行以下操作:

  • 选择POST
  • 调用 URL http://localhost:8080/student。
  • 选择身体
  • 选择他的内容类型JSON (application/json).
  • 插入数据。我们在正文中插入了以下数据:
{  
    "id": "001",  
    "age": "23",  
    "name": "Amit",  
    "email": "amit@yahoo.co.in"  
}   

  • 点击发送

请求成功执行后,会显示Status:200 OK。这意味着该记录已成功插入数据库。

同样,我们插入了以下数据。

{  
    "id": "002",  
    "age": "24",  
    "name": "Vadik",  
    "email": "vadik@yahoo.co.in"  
}   
{  
    "id": "003",  
    "age": "21",  
    "name": "Prateek",  
    "email": "prateek@yahoo.co.in"  
}   
{  
    "id": "004",  
    "age": "25",  
    "name": "Harsh",  
    "email": "harsh@yahoo.co.in"  
}   
{  
    "id": "005",  
    "age": "24",  
    "name": "Swarit",  
    "email": "Swarit@yahoo.co.in"  
}   

让我们访问 H2 控制台以查看数据。

第 20 步:打开浏览器并调用 URL http://localhost:8080/h2-console。点击连接按钮,如下图所示。

点击后Connect button, we see the Student table in the database, as shown below.

第 21 步:单击Student表,然后单击Run按钮。该表显示了我们在正文中插入的数据。

第 22 步:打开 Postman 并发送GET请求。它返回我们在数据库中插入的数据。

让我们使用 URL http://localhost:8080/student/{id}发送一个GET请求。我们调用了 URL http://localhost:8080/student/3。它返回 id 为 3 的学生的详细信息。

同样,我们也可以发送DELETE请求。假设我们要删除 id 为 2 的学生记录。

要删除学生记录,请使用 URL http://localhost:8080/student/2发送DELETE请求。我们看到 id 为2的学生已从数据库中删除。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值