Integrate H2 database(DB) in Spring Boot App
Brief about H2 DB:
H2 is an in-memory database, which has the following features :
- Open Source
- Embedded and server modes
- Very lightweight. The size of h2 DB jar is around 2MB only
- Very fast
- Written purely in Java.
- Supports Web Console
- Supports Standard SQL and JDBC API
- Multi version concurrency
- Disk based or in-memory databases and tables, read-only database support, temporary tables
- Transaction support (read committed), 2-phase-commit
and many more
What is H2 Console?
H2 is in-memory embedded database to access the database or perform some actions(CRUD operations), we can access through H2 console which is nothing but a accessing through browser.
Integration with Spring Boot:
- Step 1: Add dependency or download a jar
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency>
- Step2 : Add configuration in application.properties
* To enable H2 console
spring.h2.console.enabled=true * Access URL
spring.h2.console.path=/h2* DB URL
spring.datasource.url=jdbc:h2:file:~/db;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE* DB URL
spring.datasource.username=admin* DB PASSWORD
spring.datasource.password=adminspring.datasource.driver-class-name=org.h2.Driverspring.jpa.show-sql=truespring.jpa.hibernate.ddl-auto=update
- Note: To Enable peristent please add file location in datasource url like this
spring.datasource.url=jdbc:h2:file:~/db;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
- To Disable persistent
spring.datasource.url=jdbc:h2:mem;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
We have configure H2 DB now its time to play with H2 database.
Step3: Start the server. (start using . java -jar or any IDE).
Step 4: Now everything is ready we just need to open H2 Console.
As i have give user and password as admin while configuring so we need to provide same here.
After login we can see H2 Database console
Yay!! Its started working.
Thanks and Happy Learning.