Learn to configure H2 database with Spring boot to create and use an in-memory database in runtime, generally for unit testing or POC purposes. Remember an in-memory database is created/initialized when an application starts up; and destroyed when the application shuts down.

1. What is H2 Database?

H2 is one of the popular in-memory databases written in Java. It can be embedded in Java applications or run in the client-server mode.

Spring Boot provides excellent integration support for H2 using simple properties configuration.

To make it even more useful, H2 also provides a console view to maintain and interact with the database tables and data.

2. Maven Dependency

To use H2 in Spring boot application, all we need to do is adding H2 runtime jar into dependencies. The best way to add is through maven.

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

3. H2 Configuration Options

3.1. Simple configuration

Spring provides very easy configuration options to connect to any database using simple properties. Below are the configuration properties, we shall have in application.properties file.

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

Please note by default, Spring Boot configures the in-memory database connection with the username 'sa' and an empty password ' '. If you wish to change these values, override them in above properties options.

3.2. Configure data persistence

The in-memory databases are volatile, by default, and all stored data will be lost when we restart the application. In this case, data is written in temporary memory and as soon as JVM is stopped, data is flushed.

To have a persistent data store, which is capable to storing data between application start/stop, we should store the data in files. For this change the spring.datasource.url property.

# temporary data storage
spring.datasource.url = jdbc:h2:mem:testdb # temporary data storage
spring.datasource.url = jdbc:h2:file:/data/sample
spring.datasource.url = jdbc:h2:file:C:/data/sample (Windows only)

Read More : H2 database connection URLs

4. Create schema and insert data on initialization

We may want to initialize database with some fixed schema (DDL) and insert default data (DML) into tables before the application is ready is run business usecases.

We can achieve this by putting sql files into resources folder (/src/main/resources/).

  • schema.sql – To initialize the schema ie.create tables and dependencies.
  • data.sql – To insert default data rows.

schema.sql:

DROP TABLE IF EXISTS TBL_EMPLOYEES;

CREATE TABLE TBL_EMPLOYEES (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
email VARCHAR(250) DEFAULT NULL
);

data.sql

INSERT INTO TBL_EMPLOYEES (first_name, last_name, email) VALUES
('Lokesh', 'Gupta', 'abc@gmail.com'),
('Deja', 'Vu', 'xyz@email.com'),
('Caption', 'America', 'cap@marvel.com');

5. H2 Console

5.1. Enable H2 console

By default, the console view of H2 database is disabled. We must enable it to view and access it in browser. Note that we can customize the URL of H2 console which, by default, is '/h2'.

# Enabling H2 Console
spring.h2.console.enabled=true # Custom H2 Console URL
spring.h2.console.path=/h2

5.2. Accessing H2 console

Start the spring boot application and access the console in browser with URL : http://localhost:8080/h2.

We can see the console like this.

H2 Database Console Login Window

Now enter the configured username and password. We can verify the table structure and default data inserted through SQL files.

H2 Console View

5.3. Other configuration options

Spring boot provides two more properties to further customize the behavior of H2 console. i.e. we can enable/disable the database trace logs and we can enable/disable the remote access of H2 console.

By default both properties are false.

# Whether to enable trace output.
spring.h2.console.settings.trace=false # Whether to enable remote access.
spring.h2.console.settings.web-allow-others=false

Use these properties as per requirements at hands.

6. Conclusion

In this Spring boot with H2 database tutorial, we learned to configure, initialize and access H2 database through an spring boot application using simple properties configuration options.

Drop me your questions in comments.

Happy Learning !!

References:

[H2 DB Tutorials](

Spring Boot with H2 Database的更多相关文章

  1. Spring Boot + Mybatis + H2 database数据库

    H2 Database H2 由纯 Java 编写的开源关系数据库,可以直接嵌入到应用程序中,不受平台约束,便于测试. h2数据库特点 (1)性能.小巧 (2)同时支持网络版和嵌入式版本,另外还提供了 ...

  2. 2018-08-24 中文代码之Spring Boot对H2数据库简单查询

    续前文: 中文代码之Spring Boot集成H2内存数据库 在词条中添加英文术语域: @Entity public class 词条 { @Id private long id; private S ...

  3. 在Spring Boot使用H2内存数据库

    文章目录 添加依赖配置 数据库配置 添加初始数据 访问H2数据库 在Spring Boot使用H2内存数据库 在之前的文章中我们有提到在Spring Boot中使用H2内存数据库方便开发和测试.本文我 ...

  4. Spring Boot集成H2数据库

    需求 平时学习的时候,涉及到一些连接数据库相关的操作,经常需要初始化本地数据库,比如装个MySQL,初始化一些脚本,比较麻烦,H2是内存数据库,Spring Boot可以在应用启动的时候对H2数据库初 ...

  5. 2018-08-20 中文代码之Spring Boot集成H2内存数据库

    续前文: 中文代码之Spring Boot添加基本日志, 源码库地址相同. 鉴于此项目中的数据总量不大(即使万条词条也在1MB之内), 当前选择轻量级而且配置简单易于部署的H2内存数据库比较合理. 此 ...

  6. 中文代码之Spring Boot集成H2内存数据库

    续前文: 中文代码之Spring Boot添加基本日志, 源码库地址相同. 鉴于此项目中的数据总量不大(即使万条词条也在1MB之内), 当前选择轻量级而且配置简单易于部署的H2内存数据库比较合理. 此 ...

  7. Spring Boot Actuator H2 RCE复现

    0x00 前言 Spring Boot框架是最流行的基于Java的微服务框架之一,可帮助开发人员快速轻松地部署Java应用程序,加快开发过程.当Spring Boot Actuator配置不当可能造成 ...

  8. spring boot整合H2数据库

    一.背景: .H2数据库是一个开源的关系型数据库.H2是一个嵌入式数据库引擎,采用java语言编写,不受 平台的限制,同时支持网络版和嵌入式版本,有比较好的兼容性,支持相当标准的sql标准,支持集群. ...

  9. Spring Boot 2.x 之 H2 数据库

    1. Spring Boot下H2数据库的常用配置项 # 指定数据库的类型 spring.datasource.platform=h2 # 数据库连接地址(文件模式) ## AUTO_SERVER=T ...

随机推荐

  1. LeetCode->链表反转

    这是一个很基础的题目.今天处理了一下,不论是以双指针迭代.递归等方法,都能处理,但是也使这个题目更为典型. 剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn. ...

  2. Java_map

    1 package Test; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class MapTest { 7 p ...

  3. [atAGC046E]Permutation Cover

    每一个点都在一个排列中等价于所有排列覆盖所有位置 有解当且仅当满足$a_{y}\le 2a_{x}$(其中$a_{x}$为$a_{i}$的最小值,$a_{y}$为$a_{i}$的最大值) 证明:贪心选 ...

  4. [atARC109F]1D Kingdom Builder

    考虑最终有石子的位置的状态,判断一种状态是否可行 反过来,依次删除石子,删除条件是:当删除的石子是该段最后一个(即其两边都没有石子了),要求除其以外,每个连续段旁边的两个点都与其颜色不同 构造一种删除 ...

  5. [atARC094D]Worst Case

    首先,容易证明满足条件的$ip_{i}$必然是一个前缀 将其看成一张二分图,$i$向满足$ip_{i}<xy$的$p_{i}$连边,即找到一个前缀满足其有完美匹配 二分枚举前缀长度$k$,根据h ...

  6. [nowcoder5668H]Sort the Strings Revision

    考虑对于$p_{i}=0$,那么可以快速比较出$s_{0},s_{1},...,s_{i-1}$与$s_{i},s_{i+1},...,s_{n}$之间的大小关系,然后对两边分别找到最小的$p_{i} ...

  7. 5、使用ZSetOperations(有序)操作redis(Zset有序集合)

    文章来源:https://www.cnblogs.com/shiguotao-com/p/10564454.html 方法 c参数 s说明   void set(K key, V value); ke ...

  8. vue3 高阶 API 大汇总,强到离谱

    高阶函数是什么呢? 高阶函数英文名叫:Higher Order function ,一个函数可以接收一个或多个函数作为输入,或者输出一个函数,至少满足上述条件之一的函数,叫做高阶函数. 前言 本篇内容 ...

  9. IDEA 2021.2.3 安装与破解教程

    首先说明,大部分情况下,花10块钱都可以在淘宝找人直接帮你完美解决这个资源问题 所以千万不要相信一些所谓的百度结果,一般都是花费了时间却最后无法解决破解的问题 我相信任何一个想要学习软件开发的人一定要 ...

  10. Codeforces 840E - In a Trap(树分块+trie)

    Codeforces 题面传送门 & 洛谷题面传送门 一道非常精彩,同时也很经典的题目.和这场的 C 一样经典 首先看到这个数据范围先猜正解复杂度:\(n\) 级别大于 \(q\),所以大概是 ...