LIGHT

  • News
  • Docs
  • Community
  • Reddit
  • GitHub

H2 database

Normally H2 database is used for junit and integration test. But in some cases, for example for PoC project, we may want to use an embedded mode database, then H2 database will be a good choice to be use.

For H2 embedded mode, an application opens a database from within the same JVM using JDBC. This is the fastest and easiest connection mode.

H2 embedded mode includes two type of setting:

  1. Embedded (local) connection, the data will be saved into a local file:

For exampleL

 connection	jdbc:h2:[file:][<path>]<databaseName>
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:file:C:/data/sample (Windows only)
  1. Embedded In-memory db:

For example:

jdbc:h2:mem:<databaseName>
jdbc:h2:mem:test_mem

For H2 DB driver in the pom.xml

In the properties section, add the following line.

              <version.h2>1.3.176</version.h2>  

In the dependencies section, add the following lines (if only use h2 for junit test, add scope as “test” only).

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${version.h2}</version>
        </dependency>

Set datacource in datasource.yml config file:

#--------------------------------------------------------------------------------
# datasource.yml
#--------------------------------------------------------------------------------

datasource.H2DataSource:
  DriverClassName: org.h2.jdbcx.JdbcDataSource
  jdbcUrl: jdbc:h2:mem:testdb;INIT=runscript from 'classpath:scripts/schema.sql';
  username: sa
  password: sa
  maximumPoolSize: 2
  connectionTimeout: 500

Inject the datasource in service.yml or values.yml:

  - com.networknt.db.GenericDataSource:
      - com.networknt.db.H2DataSource:
          - java.lang.String: H2DataSource

Enable H2 db console in light4j API

Sometimes we need open DB console to verify the database. To start embedded mode h2 console, we can simply create a StartupHook:

Create a simple StartupHook

public class H2WebServerStartupHook implements StartupHookProvider {
    private static Logger logger = LoggerFactory.getLogger(H2WebServerStartupHook.class);
    @Override
    public void onStartup() {
        try {
            org.h2.tools.Server.createWebServer().start();
        } catch (SQLException e) {
            logger.error("Cannot start H2 web server!");
        }
    }
}

Add the StartupHook to service.yml:

  # StartupHookProvider implementations, there are one to many and they are called in the same sequence defined.
  - com.networknt.server.StartupHookProvider:
    - com.mservicetech.campsite.H2WebServerStartupHook

After start the API server, the H2 web console will be available in 8082 port (Note: we can change port using -webPort flag on h2 server start):

http://localhost:8082

h2-console

  • About Light
    • Overview
    • Testimonials
    • What is Light
    • Features
    • Principles
    • Benefits
    • Roadmap
    • Community
    • Articles
    • Videos
    • License
    • Why Light Platform
  • Getting Started
    • Get Started Overview
    • Environment
    • Light Codegen Tool
    • Light Rest 4j
    • Light Tram 4j
    • Light Graphql 4j
    • Light Hybrid 4j
    • Light Eventuate 4j
    • Light Oauth2
    • Light Portal Service
    • Light Proxy Server
    • Light Router Server
    • Light Config Server
    • Light Saga 4j
    • Light Session 4j
    • Webserver
    • Websocket
    • Spring Boot Servlet
  • Architecture
    • Architecture Overview
    • API Category
    • API Gateway
    • Architecture Patterns
    • CQRS
    • Eco System
    • Event Sourcing
    • Fail Fast vs Fail Slow
    • Integration Patterns
    • JavaEE declining
    • Key Distribution
    • Microservices Architecture
    • Microservices Monitoring
    • Microservices Security
    • Microservices Traceability
    • Modular Monolith
    • Platform Ecosystem
    • Plugin Architecture
    • Scalability and Performance
    • Serverless
    • Service Collaboration
    • Service Mesh
    • SOA
    • Spring is bloated
    • Stages of API Adoption
    • Transaction Management
    • Microservices Cross-cutting Concerns Options
    • Service Mesh Plus
    • Service Discovery
  • Design
    • Design Overview
    • Design First vs Code First
    • Desgin Pattern
    • Service Evolution
    • Consumer Contract and Consumer Driven Contract
    • Handling Partial Failure
    • Idempotency
    • Server Life Cycle
    • Environment Segregation
    • Database
    • Decomposition Patterns
    • Http2
    • Test Driven
    • Multi-Tenancy
    • Why check token expiration
    • WebServices to Microservices
  • Cross-Cutting Concerns
    • Concerns Overview
  • API Styles
    • Light-4j for absolute performance
    • Style Overview
    • Distributed session on IMDG
    • Hybrid Serverless Modularized Monolithic
    • Kafka - Event Sourcing and CQRS
    • REST - Representational state transfer
    • Web Server with Light
    • Websocket with Light
    • Spring Boot Integration
    • Single Page Application
    • GraphQL - A query language for your API
    • Light IBM MQ
    • Light AWS Lambda
    • Chaos Monkey
  • Infrastructure Services
    • Service Overview
    • Light Proxy
    • Light Mesh
    • Light Router
    • Light Portal
    • Messaging Infrastructure
    • Centralized Logging
    • COVID-19
    • Light OAuth2
    • Metrics and Alerts
    • Config Server
    • Tokenization
    • Light Controller
  • Tool Chain
    • Tool Chain Overview
  • Utility Library
  • Service Consumer
    • Service Consumer
  • Development
    • Development Overview
  • Deployment
    • Deployment Overview
    • Frontend Backend
    • Linux Service
    • Windows Service
    • Install Eventuate on Windows
    • Secure API
    • Client vs light-router
    • Memory Limit
    • Deploy to Kubernetes
  • Benchmark
    • Benchmark Overview
  • Tutorial
    • Tutorial Overview
  • Troubleshooting
    • Troubleshoot
  • FAQ
    • FAQ Overview
  • Milestones
  • Contribute
    • Contribute to Light
    • Development
    • Documentation
    • Example
    • Tutorial
“H2 database” was last updated: November 8, 2021: fix the image name error (#310) (e95abfe)
Improve this page
  • News
  • Docs
  • Community
  • Reddit
  • GitHub
  • About Light
  • Getting Started
  • Architecture
  • Design
  • Cross-Cutting Concerns
  • API Styles
  • Infrastructure Services
  • Tool Chain
  • Utility Library
  • Service Consumer
  • Development
  • Deployment
  • Benchmark
  • Tutorial
  • Troubleshooting
  • FAQ
  • Milestones
  • Contribute