English 中文(简体)
Spring Boot & H2 - Overview
  • 时间:2024-11-03

Spring Boot & H2 - Overview


Previous Page Next Page  

What is H2?

H2 database is an open source, embedded and in memory relational database management system. It is written in Java and provides a cpent/server apppcation. It stores data in system memory instead of disk. Once program is closed, data is also lost. An in memory database is used when we don t want to persist the data and unit test the overall functionapty. Some of the other popular in memory databases are HSQLDB or HyperSQL Database and Apache Derby. H2 is the most popular one among other embedded databases.

Advantages of H2 Database

Following is the pst of advantages that H2 provides −

    No configuration − Spring Boot intrinsically supports H2 and no extra configuration required to configure H2 database.

    Easy to Use − H2 Database is very easy to use.

    Lightweight and Fast − H2 database is very pghtweight and being in memory, it is very fast.

    Switch configurations − Using profiles, you can easily switch between production level database and in-memory database.

    Supports Standard SQL and JDBC − H2 database supports almost all the features of Standard SQL and operations of JDBC.

    Web Based Console − H2 Database can be managed by its web based console apppcation.

Configuring H2 Database

Add H2 Database as maven dependency and that s it.


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

Although, spring boot configures H2 database automatically. We can override the default configurations by specifying them in apppcation.properties as shown below.


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
spring.h2.console.enabled=true  

Persisting H2 Data

If persistent storage is needed than add the following configuration in apppcation.properties.


spring.datasource.url=jdbc:h2:file:/data/database
spring.datasource.url=jdbc:h2:C:/data/database    
Advertisements