📜  Spring Boot – H2 数据库

📅  最后修改于: 2022-05-13 01:54:59.970000             🧑  作者: Mango

Spring Boot – H2 数据库

H2 是一个嵌入式、开源和内存数据库。它是一个用Java编写的关系数据库管理系统。它是一个客户端/服务器应用程序。它将数据存储在内存中,而不是将数据持久存储在磁盘上。在这里,我们将讨论如何使用 H2 数据库在 Spring Boot 中配置和执行一些基本操作。

H2 数据库的一些主要功能是:

  • 非常快速的开源 JDBC API
  • 嵌入式和服务器模式;基于磁盘或内存中的数据库
  • 事务支持,多版本并发
  • 基于浏览器的控制台应用程序
  • 加密数据库
  • 全文搜索
  • 占用空间小的纯Java :大约 2.5 MB 的 jar 文件大小
  • ODBC 驱动程序

在 Spring Boot 应用程序中配置 H2 数据库

第一步:添加依赖

要在 Spring Boot 应用程序中使用 H2 数据库,我们必须在pom.xml文件中添加以下依赖项:

dependency>
      com.h2database
      h2
      runtime
 

第 2 步:在 application.properties 文件中写入一些属性

# 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

让我们通过打开 H2 数据库控制台来了解这些属性是什么。

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

spring.h2.console.enabled=true

一旦我们启用了 H2 控制台,现在我们可以通过调用 URL http://localhost:8082/h2-console在浏览器中访问 H2 控制台。

下图为H2数据库的控制台视图。

例子:

我们将通过创建 Spring Boot 应用程序并使用 H2 数据库来执行一些基本的 CRUD 操作。

第一步:参考这篇文章如何使用 IntelliJ IDEA 创建 Spring Boot 项目并创建一个 Spring Boot 项目。

第二步:添加以下依赖

  • 春季网络
  • H2 数据库
  • 龙目岛
  • 春季数据 JPA

下面是pom.xml文件的完整代码。请检查您是否遗漏了什么。

XML

 

    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.5
         
    
    com.amiya
    Spring-Boot-Demo-Project
    1.0.0-SNAPSHOT
    Spring-Boot-Demo-Project
    Demo project for Spring Boot
    
        11
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
 
        
            com.h2database
            h2
            runtime
        
 
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
 
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
 
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
 
        
            org.projectlombok
            lombok
            true
        
 
    
 
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    
 


Java
// Java Program to Demonstrate Department File
 
// Importing required package modules
package com.amiya.springbootdemoproject.entity;
 
// Importing required classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
 
// Class
public class Department {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    private String departmentName;
    private String departmentAddress;
    private String departmentCode;
}


Java
package com.amiya.springbootdemoproject.repository;
 
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
// Annotation
@Repository
 
// Interface extending CrudRepository
public interface DepartmentRepository
    extends CrudRepository {
}


Java
// Java Program to Demonstrate DepartmentService File
 
// Importing required package modules
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
 
// Interface
public interface DepartmentService {
 
    // Save operation
    Department saveDepartment(Department department);
 
    // Read operation
    List fetchDepartmentList();
 
    // Update operation
    Department updateDepartment(Department department,
                                Long departmentId);
 
    // Delete operation
    void deleteDepartmentById(Long departmentId);
}


Java
// Java Program to Demonstrate DepartmentServiceImpl.java
// File
 
// Importing required package modules
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;
 
// Annotation
@Service
 
// Class
public class DepartmentServiceImpl
    implements DepartmentService {
 
    @Autowired
    private DepartmentRepository departmentRepository;
 
    // Save operation
    @Override
    public Department saveDepartment(Department department)
    {
        return departmentRepository.save(department);
    }
 
    // Read operation
    @Override public List fetchDepartmentList()
    {
        return (List)
            departmentRepository.findAll();
    }
 
    // Update operation
    @Override
    public Department
    updateDepartment(Department department,
                     Long departmentId)
    {
        Department depDB
            = departmentRepository.findById(departmentId)
                  .get();
 
        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());
        }
 
        return departmentRepository.save(depDB);
    }
 
    // Delete operation
    @Override
    public void deleteDepartmentById(Long departmentId)
    {
        departmentRepository.deleteById(departmentId);
    }
}


Java
// java Program to Illustrate DepartmentController File
 
// Importing required packages modules
package com.amiya.springbootdemoproject.controller;
 
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
// Importing required classes
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
// Annotation
@RestController
 
// Class
public class DepartmentController {
 
    @Autowired private DepartmentService departmentService;
 
    // Save operation
    @PostMapping("/departments")
    public Department saveDepartment(
        @Valid @RequestBody Department department)
    {
        return departmentService.saveDepartment(department);
    }
 
    // Read operation
    @GetMapping("/departments")
    public List fetchDepartmentList()
    {
        return departmentService.fetchDepartmentList();
    }
 
    // Update operation
    @PutMapping("/departments/{id}")
    public Department
    updateDepartment(@RequestBody Department department,
                     @PathVariable("id") Long departmentId)
    {
        return departmentService.updateDepartment(
            department, departmentId);
    }
 
    // Delete operation
    @DeleteMapping("/departments/{id}")
    public String deleteDepartmentById(@PathVariable("id")
                                       Long departmentId)
    {
        departmentService.deleteDepartmentById(
            departmentId);
        return "Deleted Successfully";
    }
}



第 3 步:创建 4 个包,然后在这些包中创建一些类和接口,如下图所示

  • 实体
  • 存储库
  • 服务
  • 控制器

第 4 步:在实体包内

在 Department 内部创建一个简单的 POJO 类。 Java文件。

例子:

Java

// Java Program to Demonstrate Department File
 
// Importing required package modules
package com.amiya.springbootdemoproject.entity;
 
// Importing required classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
 
// Class
public class Department {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    private String departmentName;
    private String departmentAddress;
    private String departmentCode;
}


第 5 步:在存储库包中

创建一个简单的接口并将接口命名为 DepartmentRepository。正如我们上面讨论的那样,这个接口将扩展 CrudRepository。

示例下面是DepartmentRepository 的代码。Java

Java

package com.amiya.springbootdemoproject.repository;
 
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
// Annotation
@Repository
 
// Interface extending CrudRepository
public interface DepartmentRepository
    extends CrudRepository {
}


第 6 步:在服务包内

在包中创建一个名为DepartmentService的接口和一个名为DepartmentServiceImpl的类。

示例 1-A

Java

// Java Program to Demonstrate DepartmentService File
 
// Importing required package modules
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;
 
// Interface
public interface DepartmentService {
 
    // Save operation
    Department saveDepartment(Department department);
 
    // Read operation
    List fetchDepartmentList();
 
    // Update operation
    Department updateDepartment(Department department,
                                Long departmentId);
 
    // Delete operation
    void deleteDepartmentById(Long departmentId);
}


示例 1-B

Java

// Java Program to Demonstrate DepartmentServiceImpl.java
// File
 
// Importing required package modules
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;
 
// Annotation
@Service
 
// Class
public class DepartmentServiceImpl
    implements DepartmentService {
 
    @Autowired
    private DepartmentRepository departmentRepository;
 
    // Save operation
    @Override
    public Department saveDepartment(Department department)
    {
        return departmentRepository.save(department);
    }
 
    // Read operation
    @Override public List fetchDepartmentList()
    {
        return (List)
            departmentRepository.findAll();
    }
 
    // Update operation
    @Override
    public Department
    updateDepartment(Department department,
                     Long departmentId)
    {
        Department depDB
            = departmentRepository.findById(departmentId)
                  .get();
 
        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());
        }
 
        return departmentRepository.save(depDB);
    }
 
    // Delete operation
    @Override
    public void deleteDepartmentById(Long departmentId)
    {
        departmentRepository.deleteById(departmentId);
    }
}


第 7 步:在控制器包内

在包中创建一个名为DepartmentController的类。

例子

Java

// java Program to Illustrate DepartmentController File
 
// Importing required packages modules
package com.amiya.springbootdemoproject.controller;
 
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
// Importing required classes
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
// Annotation
@RestController
 
// Class
public class DepartmentController {
 
    @Autowired private DepartmentService departmentService;
 
    // Save operation
    @PostMapping("/departments")
    public Department saveDepartment(
        @Valid @RequestBody Department department)
    {
        return departmentService.saveDepartment(department);
    }
 
    // Read operation
    @GetMapping("/departments")
    public List fetchDepartmentList()
    {
        return departmentService.fetchDepartmentList();
    }
 
    // Update operation
    @PutMapping("/departments/{id}")
    public Department
    updateDepartment(@RequestBody Department department,
                     @PathVariable("id") Long departmentId)
    {
        return departmentService.updateDepartment(
            department, departmentId);
    }
 
    // Delete operation
    @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

现在运行您的应用程序,让我们在 Postman 中测试端点并参考我们的 H2 数据库。

在 Postman 中测试端点

端点 1: POST – http://localhost:8082/departments/

端点 2: GET - http://localhost:8082/departments/

端点 3: PUT - http://localhost:8082/departments/1

端点 4:删除 - http://localhost:8082/departments/1

最后,H2 数据库如下图所示: 如下: