H2 Usage

2024-07-02
2 min read

h2 features are Very fast, open source, JDBC API, Embedded and server modes; in-memory databases, Browser based Console application, Small footprint: around 2.5 MB jar file size.

Dependence

Add d2 dependence, You need jpa because wanna ddl-auto feature, It make project generate and apply the create tables automatically.Need mybatis dependence for sure.Fortunately they do not conflict.Note that the h2’s JDBC driver have been include in the h2 dependence.

<!-- Spring Boot Starter Data JPA -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>3.0.3</version>
</dependency>
<!-- H2 Database -->
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

Config

In the application-$env.yaml the most important config is spring.datasource.Of course there need to restore programming data.When springboot starup,there generated ~/.h2/h2.mv.db, ~/.h2/h2.trace.db, ~/.h2/h2.lock.db files which are stored the ddl logs and process lock information respectively.For mybatis just use it commonly.

spring:
  datasource:
    url: jdbc:h2:file:~/.h2/h2;AUTO_SERVER=TRUE
    username: sa
    password: ******
    driverClassName: org.h2.Driver
    platform: h2
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
mybatis:
  type-aliases-package: com.neoemacs.tool.server.po
  configuration:
    map-underscore-to-camel-case: true

Each d2 database program only support a single client concurrently defaut.Use `AUTO_SERVER=TRUE` break it.

ejc Connection

Use ejc connect h2 database,thing going to be done finding a h2 jdbc driver,usually you could find it under maven repository director,after that just enjoy it.

(ejc-create-connection "H2"
 :classpath (file-truename
      "~/.m2/repository/com/h2database/h2/2.2.224/h2-2.2.224.jar")
 :subprotocol "h2"
 :subname     "~/.h2/h2;AUTO_SERVER=TRUE"
 :user        "sa"
 :password    "*****"
 :separator   "</?\.*>")