Spring Boot with H2
In this tutorial, we will examine the usage of the in-memory database h2 in a Spring Boot application.
H2 is an in-memory database, we can use it for simple case-studies and quick show cases.
The dependency for Spring Data and JPA:
The dependency for H2:
When the applications starts, we can access the GUI by navigating to:
http://localhost:8080/h2-console
For more information about H2 database you can refer to:
http://www.h2database.com
H2 is an in-memory database, we can use it for simple case-studies and quick show cases.
Maven Dependencies
This can be easily generated with Spring Starter.The dependency for Spring Data and JPA:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
The dependency for H2:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
H2 Configuration
Now, we can configure the database settings in application.properties file:spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
The last line is for accessing H2 GUI console to query the database via SQL statements.When the applications starts, we can access the GUI by navigating to:
http://localhost:8080/h2-console
Initial Data
To create initial tables and insert sample data into the tables, Spring Boot reads the file data.sql and runs ddl and dml in the file.CREATE TABLE books (
id INT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
author VARCHAR(120) NOT NULL
);
INSERT INTO books (id, name, author)
VALUES
(1, 'Java Persistence', 'John Mohn'),
(2, 'H2 Database', 'Lhan Mhan');
For more information about H2 database you can refer to:
http://www.h2database.com
Yorumlar
Yorum Gönder