SpringBoot整合H2數(shù)據(jù)庫的操作方法
1、H2數(shù)據(jù)庫概述
H2官網(wǎng):http://www.h2database.com/
H2是一個(gè)Java語言編寫的嵌入式數(shù)據(jù)庫,它不受平臺(tái)的限制,同時(shí)H2提供了一個(gè)十分方便的web控制臺(tái),用于操作和管理數(shù)據(jù)庫內(nèi)容。H2還提供兼容模式,可以兼容一些主流的數(shù)據(jù)庫,也可以為緩存數(shù)據(jù)庫使用,它具有比較完備的數(shù)據(jù)庫特性,如支client/server連接,能夠支持標(biāo)準(zhǔn)的SQL語句,支持存儲(chǔ)過程等。因此采用H2作為開發(fā)期、測試期和演示的數(shù)據(jù)庫非常方便,它不太適合作為大規(guī)模生產(chǎn)數(shù)據(jù)庫。
H2數(shù)據(jù)庫的前身是 HypersonicSQL,它的名字的含義是 Hypersonic2,但是它的代碼是從頭開始編寫的,沒有使用HypersonicSQL或者HSQLDB的代碼。
H2特點(diǎn):
- 運(yùn)行很快,開源,支持 JDBC API;
- 支持嵌入模式和服務(wù)器模式;
- 基于磁盤或內(nèi)存中的數(shù)據(jù)庫;
- 基于瀏覽器控制臺(tái)應(yīng)用程序;
- 文件很小,jar文件約 1.5 MB
- 加密數(shù)據(jù)庫;
- ODBC 驅(qū)動(dòng)程序;
H2控制臺(tái)應(yīng)用程序
通過控制臺(tái)應(yīng)用程序,我們就可以使用瀏覽器訪問H2數(shù)據(jù)庫了,數(shù)據(jù)庫管理界面類似phpmyadmin。

H2文檔地址:http://www.h2database.com/html/quickstart.html
使用方式:
集成h2也很簡單,直接將jar包導(dǎo)入項(xiàng)目中即可。
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
<scope>test</scope>
</dependency>2、SpringBoot整合H2
1、創(chuàng)建一個(gè)SpringBoot工程

2、導(dǎo)入mp和h2相關(guān)依賴:
<!--springmvc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--h2數(shù)據(jù)庫-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<!--version:1.4.200-->
<scope>compile</scope>
</dependency>
<!--mp-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!--mysql驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>3、向application.yml文件中添加配置:
server:
port: 8888 # 端口號
spring:
datasource:
url: jdbc:h2:~/mydb # 數(shù)據(jù)庫
driver-class-name: org.h2.Driver
username: root
password: test
h2:
console:
path: /h2-console #h2嵌入式數(shù)據(jù)庫控制臺(tái),可以通過瀏覽器訪問
enabled: true
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 開啟sql日志
map-underscore-to-case: true # 開啟駝峰映射(mp默認(rèn)開啟)username和password是H2數(shù)據(jù)庫的用戶名和密碼,自己定義即可。/h2-console是自定義的控制臺(tái)地址,用戶可以打開瀏覽器,進(jìn)入這個(gè)地址管理數(shù)據(jù)庫,使用上面配置的username和password登錄。
4、編寫業(yè)務(wù)代碼:
實(shí)體類:
package com.baidou.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 實(shí)體類
*
* @author 白豆五
* @version 2023/04/4
* @since JDK8
*/
@Data
@TableName(value = "tb_user")
public class User {
private Integer id;
private String username;
private String pwd;
private Integer salary;//以分為單位,避免浮點(diǎn)運(yùn)算精度丟失問題
// 封裝數(shù)據(jù)
public void setSalary(Integer salary) {
this.salary = salary * 100;
}
}mapper接口:
package com.baidou.mapper;
import com.baidou.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
//mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}service接口:
package com.baidou.service;
import com.baidou.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
// service接口
public interface UserService extends IService<User> {
}service接口實(shí)現(xiàn)類:
package com.baidou.service.impl;
import com.baidou.entity.User;
import com.baidou.mapper.UserMapper;
import com.baidou.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* service接口實(shí)現(xiàn)類
*
* @author 白豆五
* @version 2023/04/4
* @since JDK8
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}5、在resources目錄下,創(chuàng)建一個(gè)db/schema-h2.sql文件:
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user(
id INT(11) PRIMARY KEY AUTO_INCREMENT COMMENT 'id',
username VARCHAR(30) NOT NULL UNIQUE COMMENT '用戶名',
pwd VARCHAR(10) NOT NULL COMMENT '密碼',
salary INT NULL DEFAULT 0 COMMENT '薪資'
);
6、實(shí)現(xiàn)讓服務(wù)啟動(dòng)時(shí)自動(dòng)執(zhí)行DDL語句,并且只讓它第一次啟動(dòng)時(shí)自動(dòng)創(chuàng)建數(shù)據(jù)庫,后續(xù)項(xiàng)目啟動(dòng)都不會(huì)重新創(chuàng)建(避免數(shù)據(jù)丟失)
① 定義一個(gè)類去實(shí)現(xiàn)ApplicationContextAware接口,然后在類上添加@Component注解,代表當(dāng)前類是spring的bean。
package com.baidou.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
/**
* 定義一個(gè)注冊器策略類,方便后續(xù)加載資源文件
*
* ApplicationContextAware是Spring框架提供的接口,也叫做spring上下文的增強(qiáng)器,在項(xiàng)目啟動(dòng)時(shí)執(zhí)行,會(huì)被spring處理
* 當(dāng)一個(gè)bean實(shí)現(xiàn)了該接口,通過setApplicationContext方法可以直接獲取spring容器中的所有bean
*/
@Component
public class ApplicationContextRegister implements ApplicationContextAware {
private ApplicationContext applicationContext = null;
/**
* Spring容器啟動(dòng)時(shí),會(huì)回調(diào)setApplicationContext方法,并傳入ApplicationContext對象,之后就可對該對象進(jìn)行操作。(例如獲取spring容器中的所有bean)
*
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 提供一個(gè)方法,用于加載sql腳本文件
*
* @param url sql文件位置
* @return
*/
public Resource getResource(String url) {
return this.applicationContext.getResource(url);
}
}ApplicationContextAware接口詳解:https://www.cnblogs.com/loongk/p/12375708.html
② 編寫初始化數(shù)據(jù)庫代碼:
package com.baidou.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;
/**
* 初始化h2數(shù)據(jù)庫
*/
@Slf4j
@Service
@AutoConfigureAfter(DataSource.class) //DataSource創(chuàng)建完后才初始化此類
public class H2DataSourceConfig {
//初始化sql
private static final String schema="classpath:db/schema-h2.sql";
@Autowired
DataSource dataSource;
@Autowired
ApplicationContextRegister applicationContextRegister; //自定義注冊器
// JDK提供的注解,在方法上加該注解會(huì)在項(xiàng)目啟動(dòng)的時(shí)候執(zhí)行該方法,也可以理解為在spring容器初始化的時(shí)候執(zhí)行該方法
@PostConstruct
public void init() throws Exception {
//初始化本地?cái)?shù)據(jù)庫
String userHome= System.getProperty("user.home");//獲取系統(tǒng)用戶目錄
// 創(chuàng)建一個(gè)標(biāo)識(shí)文件,只有在第一次初始化數(shù)據(jù)庫時(shí)會(huì)創(chuàng)建,如果系統(tǒng)用戶目錄下有這個(gè)文件,就不會(huì)重新執(zhí)行sql腳本
File f = new File(userHome+ File.separator+"my.lock");
if(!f.exists()){
log.info("--------------初始化h2數(shù)據(jù)----------------------");
f.createNewFile();
// 加載資源文件
Resource resource= (Resource) applicationContextRegister.getResource(schema);
// 手動(dòng)執(zhí)行SQL語句
ScriptUtils.executeSqlScript(dataSource.getConnection(),resource);
}
}
}7、啟動(dòng)項(xiàng)目,然后瀏覽器訪問:http://localhost:8888/h2-console
輸入之前在application.yml中h2的相關(guān)配置;如用戶名、密碼、數(shù)據(jù)庫名


8、創(chuàng)建一個(gè)測試類,然后使用MP操作H2數(shù)據(jù)庫
執(zhí)行單元測試的時(shí)候先將項(xiàng)目停止,不然匯報(bào)H2數(shù)據(jù)庫文件鎖定問題。(默認(rèn)單線程模式)
package com.baidou.test;
import com.baidou.entity.User;
import com.baidou.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* 使用MP操作H2數(shù)據(jù)庫
*
* @author 白豆五
* @version 2023/04/4
* @since JDK8
*/
@SpringBootTest
public class H2Test {
@Autowired
private UserService userService;
@Test
public void test1() {
User user = new User();
user.setId(1);
user.setUsername("張三");
user.setPwd("123456e");
user.setSalary(10000); //10k
boolean flag = userService.save(user);
System.out.println(flag ? "插入成功" : "插入失敗");
}
@Test
public void test2() {
List<User> list = userService.list();
System.out.println(list);
}
}運(yùn)行結(jié)果:

重新啟動(dòng)項(xiàng)目,再次通過瀏覽器訪問h2控制臺(tái):

3、 擴(kuò)展 :基于文件模式將H2數(shù)據(jù)庫持久化

H2數(shù)據(jù)庫在文件模式下會(huì)生成: xxx.mv.db和xxx.trace.db文件。
xxx.mv.db是H2數(shù)據(jù)庫的主文件,用于保存數(shù)據(jù)表的結(jié)構(gòu)和數(shù)據(jù)。xxx.trace.db是H2數(shù)據(jù)庫的跟蹤文件,用于記錄數(shù)據(jù)庫的操作和日志信息。

到此這篇關(guān)于SpringBoot整合H2數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)SpringBoot整合H2數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合Swagger3全注解配置(springdoc-openapi-ui)
本文主要介紹了Springboot整合Swagger3全注解配置(springdoc-openapi-ui),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
解決java啟動(dòng)時(shí)報(bào)線程占用報(bào)錯(cuò):Exception?in?thread?“Thread-14“?java.ne
這篇文章主要給大家介紹了關(guān)于解決java啟動(dòng)時(shí)報(bào)線程占用:Exception?in?thread?“Thread-14“?java.net.BindException:?Address?already?in?use:?bind的相關(guān)資料,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04
spring @Profiles和@PropertySource實(shí)現(xiàn)根據(jù)環(huán)境切換配置文件
這篇文章主要介紹了spring @Profiles和@PropertySource根據(jù)環(huán)境切換配置文件,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java線程安全的常用類_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
在集合框架中,有些類是線程安全的,這些都是jdk1.1中的出現(xiàn)的。在jdk1.2之后,就出現(xiàn)許許多多非線程安全的類。 下面是這些線程安全的同步的類2017-06-06
詳解Spring Boot配置文件application.properties
在本文中我們給大家整理了關(guān)于Spring Boot 的配置文件 application.properties的相關(guān)知識(shí)點(diǎn)內(nèi)容,需要的朋友們參考學(xué)習(xí)下。2019-06-06

