在本教程中,我们将展示如何使用 JDBC 模板集成Spring Boot H2 数据库。
Spring Boot H2 数据库:
Spring Boot 提供了一个名为 H2 数据库的内存数据库,主要用于开发快速 POC 和单元级测试时。
如何启用 Spring Boot H2 数据库:
步骤1:
在 pom.xml 中添加以下 H2 依赖项
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
第2步:
通过在 application.properties 文件中设置spring.h2.console.enabled属性,在Spring Boot 应用程序中启用 H2-console 。
application.properties
spring.h2.console.enabled=true
在运行您的 Spring Boot 应用程序后允许使用 h2-console。完成这两个步骤后,您可以在浏览器上看到 H2 控制台,如下所示。
访问应用网址: http://localhost:8080/h2-console/
输入 JDBC URL 作为jdbc:h2:mem:testdb并单击 Connect。
注意:将密码保留为黑色。
然后你可以看到下面带有默认模式的 H2 主控制台。
现在我们可以使用这个 H2 DB 并在testdb下创建我们的模式。
作为本教程的一部分,我将在testdb下创建一个简单的Item表,并对Item表执行必要的 CRUD 操作。
Spring Boot H2 数据库示例:
技术:
- Spring Boot 1.5.10.RELEASE
- H2 数据库
- Spring Boot Starter JDBC
- Java8
项目结构:
<?xml version="1.0" encoding="UTF-8"?>
<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.onlinetutorialspoint</groupId>
<artifactId>SpringBoot_H2_Database</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot_H2_Database</name>
<description>Demo project for Spring Boot H2 Database</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
应用程序属性
application.properties
spring.h2.console.enabled=true
准备数据库模式:
在/resources文件夹下创建 schema.sql 和 data.sql 文件,以便 spring boot 在加载应用程序时选择这些文件来准备数据库。
架构.sql
创建具有数据库模式的 schema.sql。
schema.sql
CREATE TABLE `item` (
`id` INT(11) NOT NULL,
`name` VARCHAR(50) NULL DEFAULT NULL,
`category` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
数据.sql
创建具有模式数据的data.sql。
data.sql
INSERT INTO `item` (`id`, `name`, `category`) VALUES (1, 'IPhone 6S', 'Mobile');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (2, 'Samsung Galaxy', 'Mobile');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (3, 'Lenovo', 'Laptop');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (4, 'LG', 'Telivision');
创建项目模型:
Item.java
package com.onlinetutorialspoint.model;
public class Item {
private int id;
private String name;
private String category;
public Item() {
}
public Item(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
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 String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
创建项目存储库:
package com.onlinetutorialspoint.repository;
import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class ItemRepository {
@Autowired
JdbcTemplate template;
/*Getting all Items from table*/
public List<Item> getAllItems(){
List<Item> items = template.query("select id, name,category from item",(result,rowNum)->new Item(result.getInt("id"),
result.getString("name"),result.getString("category")));
return items;
}
/*Getting a specific item by item id from table*/
public Item getItem(int itemId){
String query = "SELECT * FROM ITEM WHERE ID=?";
Item item = template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));
return item;
}
/*Adding an item into database table*/
public int addItem(int id,String name,String category){
String query = "INSERT INTO ITEM VALUES(?,?,?)";
return template.update(query,id,name,category);
}
/*delete an item from database*/
public int deleteItem(int id){
String query = "DELETE FROM ITEM WHERE ID =?";
return template.update(query,id);
}
}
创建休息控制器:
ItemController.java
package com.onlinetutorialspoint.controller;
import java.util.List;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ItemController {
@Autowired
ItemRepository itemRepo;
@RequestMapping("/getAllItems")
@ResponseBody
public List<Item> getAllItems(){
return itemRepo.getAllItems();
}
@RequestMapping("/getItem")
@ResponseBody
public Item getItem(@RequestParam("itemId") int itemId){
return itemRepo.getItem(itemId);
}
@RequestMapping("/addItem")
@ResponseBody
public String addItem(@RequestParam("id") int id,@RequestParam("name") String name,
@RequestParam("category") String category){
if(itemRepo.addItem(id,name,category) >= 1){
return "Item Added Successfully";
}else{
return "Something went wrong !";
}
}
@RequestMapping("/deteteItem")
@ResponseBody
public String deteteItem(@RequestParam("itemId") int itemId){
if(itemRepo.deleteItem(itemId) >= 1){
return "Item Deleted Successfully";
}else{
return "Something went wrong !";
}
}
}
运行应用程序:
mvn clean install
mvn spring-boot:run
2018-02-22 08:34:26.024 INFO 7644 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/E:/work/SpringBoot_H2_Database/target/classes
/schema.sql]
2018-02-22 08:34:26.040 INFO 7644 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/E:/work/SpringBoot_H2_Database/target/classes/
schema.sql] in 16 ms.
2018-02-22 08:34:26.040 INFO 7644 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/E:/work/SpringBoot_H2_Database/target/classes
/data.sql]
2018-02-22 08:34:26.055 INFO 7644 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/E:/work/SpringBoot_H2_Database/target/classes/
data.sql] in 0 ms.
您可以在运行上述应用程序时观察脚本执行情况。
再次访问H2-console以查看我们的Item表和数据。
访问应用:
获取所有项目:
获取单项:
从 H2 中删除项目:
将项目添加到 H2 :
添加和删除后获取所有项目:
参考:
快乐学习🙂
下载示例
- SpringBoot_H2_Database
文件大小: 89 KB 下载次数: 2449