Spring Boot - H2数据库

Spring Boot - H2数据库 首页 / Spring Boot入门教程 / Spring Boot - H2数据库

什么是内存数据库

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

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

持久性与内存数据库

持久数据库将数据持久存储在物理内存中。即使数据库服务器死机,数据也将可用。一些流行的持久性数据库是 Oracle , MySQL , Postgres 等。

对于内存数据库,数据存储在系统内存中。当程序关闭时,它丢失了数据。广泛使用的内存数据库是 H2

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 是文件名。

创建表并填充数据

可以通过在 resource 文件夹(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,
);

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

data.sql

INSERT INTO CITY VALUES ('Delhi', 110001);
INSERT INTO CITY VALUES ('Kanpur', 208001);
INSERT INTO CITY VALUES ('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数据库的控制台视图。

Spring Boot H2 Database

Spring Boot H2示例

让无涯教程使用H2数据库设置一个Spring Boot应用程序。

步骤1 - 打开Spring Initializr http://start.spring.io 。

步骤2 - 选择Spring Boot版本 2.3.0.M1。

步骤3 - 填写Group名称。

步骤4 - 填写Artifact ID。提供了 spring-boot-h2-database-example

步骤5 - 添加依赖项 Spring Web,Spring Data JPA H2数据库

步骤6 - 单击 Generate (生成)按钮。当单击"Gennerate"按钮时,它会将项目包装在 Jar 文件中,并将其下载到本地系统。

Spring Boot H2 Database

步骤7 - 提取 Jar文件并将其粘贴到STS工作区中。

步骤8 - 导入项目文件夹到STS中。

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-h2-database-example -> Finish

步骤9 - 在文件夹 src/main/java中创建一个名称为 com.learnfk.model 的软件包。

步骤10 - 在包 com.learnfk.model中创建模型类。 无涯教程创建了名为 Student的模型类。 在"Book"类中,执行了以下操作:

  • 定义四个变量 id, age, name, and Email
  • 生成Getters和Setters。右键点击 file -> Source -> Generate Getters and Setters.
  • 使用注释@Entity将类标记为Entity。
  • 使用注解@Table将类标记为表名称。
  • 使用注释@Column将每个变量定义为Column。

Student.java

package com.learnfk.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Student 
{
  @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;
  }
}

步骤11 - 在文件夹 src/main/java中创建一个名称为 com.learnfk.controller 的软件包。

步骤12 - 在包 com.learnfk.controller 中创建一个Controller类。已经创建了名称为 StudentController 的控制器类。在StudentController类中,执行了以下操作:

  • 通过使用注释 @RestController将类标记为 RestController 使用注释 @Autowired
  • 自动连接 StudentService 类。
  • 定义以下方法:
    • getAllStudent()   -   它返回所有学生的列表。
    • getStudent()         -  它返回在path变量中指定的学生详细信息。通过使用注释@PathVariable,已将id作为参数传递。
    • deleteStudent()   -  它将删除在path变量中指定的特定学生。
    • saveStudent()       -  保存学生的详细信息。注释@RequestBody表示应将方法参数绑定到Web请求的正文。
  • StudentController.java

    package com.learnfk.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.learnfk.model.Student;
    import com.learnfk.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 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.learnfk.service 的软件包。

    步骤14 - 创建一个服务类。无涯教程在包 com.learnfk.service 中创建了一个名为 StudentService 的服务类。

    StudentService.java

    package com.learnfk.service;
    import java.util.ArrayList;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import com.learnfk.model.Student;
    import com.learnfk.repository.StudentRepository;
    @Service
    public class StudentService 
    {
      @Autowired
      StudentRepository studentRepository;
     
      public List<Student> getAllStudent() 
      {
        List<Student> students = new ArrayList<Student>();
        studentRepository.findAll().forEach(student -> students.add(student));
        return students;
      }
      public Student getStudentById(int id) 
      {
        return studentRepository.findById(id).get();
      }
      public void saveOrUpdate(Student student) 
      {
        studentRepository.save(student);
      }
      
      public void delete(int id) 
      {
        studentRepository.deleteById(id);
      }
    }

    步骤15 -  src/main/java文件夹中创建一个名称为 com.learnfk.repository 的软件包。

    步骤16 - 创建一个存储库接口。在包 com.learnfk.repository中创建了一个名为 StudentRepository 的接口。 它扩展了 Crud存储库接口。

    StudentRepository.java

    package com.learnfk.repository;
    import org.springframework.data.repository.CrudRepository;
    import com.learnfk.model.Student;
    public interface StudentRepository extends CrudRepository
    {
    }

    现在,无涯教程将在 application.properties 文件中配置数据源 URL,驱动程序类名称,用户名密码

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

    application.properties

    spring.datasource.url=jdbc:h2:mem:learnfk
    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

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

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

    Spring Boot H2 Database

    现在,无涯教程将运行该应用程序。

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

    SpringBootH2DatabaseExampleApplication.java

    package com.learnfk;
    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);
    }
    }

    下一步,将使用其余客户端 Postman 发送 POST GET 请求。 

    步骤19 - 打开POSTMAN并执行以下操作:

    • 选择 POST
    • 调用URL http:// localhost:8080/student。
    • 选择Body
    • 选择内容类型 JSON(应用程序/ json)。
    • 插入数据。在正文中插入了以下数据:
    {
        "id": "001",
        "age": "23",
        "name": "Amit",
        "email": "amit@yahoo.co.in"
    } 
    • 点击Send

    成功执行请求后,它会显示状态: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。点击连接按钮,如下所示。

    Spring Boot H2 Database

    单击连接按钮后,将在数据库中看到STUDENT表,如下所示。

    Spring Boot H2 Database

    步骤21 - 单击STUDENT表,然后单击Run按钮。该表显示了无涯教程插入到正文中的数据。

    Spring Boot H2 Database

    步骤22 - 打开POSTMAN并发送 GET 请求。它返回已插入数据库中的数据。

    Spring Boot H2 Database

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

    Spring Boot H2 Database

    同样,也可以发送 Delete 请求。假设要删除ID为2的学生记录。

    要删除学生记录,请发送带有URL http:// localhost:8080/student/2的 Delete 请求。无涯教程发现ID为 2 的学生已从数据库中删除。

    Spring Boot H2 Database

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

硅谷产品实战36讲 -〔曲晓音〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

Kafka核心技术与实战 -〔胡夕〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

MySQL 必知必会 -〔朱晓峰〕

全链路压测实战30讲 -〔高楼〕

深入剖析Java新特性 -〔范学雷〕

中间件核心技术与实战 -〔丁威〕

商业思维案例笔记 -〔曹雄峰〕

好记忆不如烂笔头。留下您的足迹吧 :)