什么是内存数据库
内存数据库依赖于系统内存而不是磁盘数据存储空间。因为内存访问比磁盘访问快。当我们不需要持久化数据时,我们使用内存数据库。内存数据库是嵌入式数据库。默认情况下,内存数据库是易失性的,当我们重新启动应用程序时,所有存储的数据都会丢失。
广泛使用的内存数据库是 H2,HSQLDB (HyperSQL数据库) ,和 Apache Derby。 它会自动创建配置。
持久性与内存数据库
持久性数据库将数据持久存储在物理内存中。即使数据库服务器退回,数据也将可用。一些流行的持久性数据库是 Oracle , MySQL , Postgres ,等。
在对于 内存数据库,数据存储在 系统内存中。程序关闭时丢失了数据。它对 POC (概念证明)很有帮助,而不对生产应用程序有用。广泛使用的内存数据库是 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 是一个文件名。
创建Schema构并填充数据
我们可以定义通过在 resource 文件夹(src)中创建 SQL 文件创建架构/main/resource)。
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:8089/h2-console在浏览器中访问H2控制台。下图显示了H2数据库的控制台视图。

 

 

<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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.tszy</groupId>
    <artifactId>H2</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- DevTools in Spring Boot 项目热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
server.port=8089

spring.datasource.url=jdbc:h2:mem:lidihuo
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
package com.lidihuo.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;
    }
}
package com.lidihuo.model;

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.lidihuo.model.Student;
import com.lidihuo.model.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();
    }
}
package com.lidihuo.model;

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

@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);
    }

}
package com.lidihuo.model;

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

public interface StudentRepository extends CrudRepository<Student, Integer>
{
}
package com.lidihuo.model;

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);
    }
}

 

 

打开浏览器并调用URL http://localhost:8089/h2-console。单击 Connect 按钮,如下所示。

 

 

 

 

单击 Student表,然后单击 运行按钮。该表显示了我们插入到正文中的数据。

 

 

 打开Postman并发送 GET 请求。它返回我们已经插入数据库中的数据。

 

 

调用了URL http://localhost:8080/student/3。它返回ID为3的学生的详细信息。

 

 

假设我们要删除ID为2的学生记录。
要删除学生记录,请发送带有URL http://localhost:8089/student/的 DELETE 请求。我们看到ID为 2 的学生已从数据库中删除。