
- Spring Boot & H2 Tutorial
- Spring Boot & H2 - Home
- Spring Boot & H2 - Overview
- Spring Boot & H2 - Environment Setup
- Spring Boot & H2 - Project Setup
- Spring Boot & H2 - REST APIs
- Spring Boot & H2 - H2 Console
- Spring Boot & H2 Examples
- Spring Boot & H2 - Add Record
- Spring Boot & H2 - Get Record
- Spring Boot & H2 - Get All Records
- Spring Boot & H2 - Update Record
- Spring Boot & H2 - Delete Record
- Spring Boot & H2 - Unit Test Controller
- Spring Boot & H2 - Unit Test Service
- Spring Boot & H2 - Unit Test Repository
- Spring Boot & H2 Useful Resources
- Spring Boot & H2 - Quick Guide
- Spring Boot & H2 - Useful Resources
- Spring Boot & H2 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Spring Boot & H2 - Overview
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 client/server application. 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 functionality. 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 list 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 lightweight 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 application.
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 application.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 application.properties.
spring.datasource.url=jdbc:h2:file:/data/database spring.datasource.url=jdbc:h2:C:/data/database