Spring boot H2 Database example

In this post, we are going to see how to create Spring boot application integrating with H2 database.


What is H2 database?

H2 is open source database. It is very fast and smaller in size. It is in-memory database and keeps all data in memory. If you start and stop the application, all the data will be erased as it is not persisted. Although there is an option to persist the data on the disk as well with H2 database.

H2 database is not recommended for production environment and is suitable for small applications which require very simple database.


Tools used

  • Spring Boot 2.2.2.RELEASE
  • Spring JDBC 5.2.2.RELEASE
  • HikariCP 3.4.1
  • Maven 3
  • Java 8

Github Source code:

Here are steps to create a Spring boot H2 database example.


Project Structure

SpringH2DatabaseProjectStructure


Create new Spring boot project

Step 1:  Go to start.spring.io and create a project with following dependencies

  • Spring web
  • H2 database
  • Spring data jpa

Here is the screenshot for the same.
Spring Boot Spring io


Maven configuration

Step 2: You should have pom.xml as below:

The spring-boot-starter-parent provides you all maven defaults required for any spring project.


H2 database configuration

As we already know Spring boot is opinionated framework and it will do lots of autoconfigurations based on dependencies available in class path.

In this case, we have H2 dependencies in our classpath, so Spring boot automatically configures some default properties such as URL, username and password.

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

We don’t have to configure anything in case you are fine with these defaults. It uses schema name as testdb.

Can we override defaults?
Oh yes, you can


Override H2 databse defaults

You can always override any property by putting it in application.properties.
For example:
Let’s say you want override property spring.h2.console.enable and want to change it true
You can put this property in application.properties as below.


Model

Step 3: Create model class named Movie.java

@Entity is used for making a persistent pojo class.For this java class,you will have corresponding table in database.


Repository

Step 4: Create a MovieRepository interface which will extend CrudRepository. We don’t have to provide implementaton, Spring data will autmatically do it for us.


Service

Step 5: Create a service class “MovieService” and autowire MovieRepository in service class.


Controller

Step 6: Create a file named “MovieController.java” in package .org.arpit.java2blog.controller and autowire MovieService in MovieController.


Spring boot main file

Step 7: Create a file named SpringBootH2ExampleApplication.java in package .org.arpit.java2blog

We have just added @SpringBootApplication and it does all the work.
Let’s understand more about this annotation.
@SpringBootApplication is an annotation that adds all of the following:

  • @Configuration makes the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration enables Spring boot to add beans present in classpath setting and various property setting.
  • Normally you would add @EnableWebMvc for a Spring MVC application, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
    This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

    @ComponentScan tells Spring to look for other components, configurations, and services in the default package, allowing it to find the controllers.
    If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.


Run the application

Step 8: Let’s start and run the appliation.
Let’s open H2 console now.

  1. Go to url http://localhost:8080/h2-console
  2. SpringBootH2DatabaseURL
    Please make sure JDBC URL is jdbc:h2:mem:testdb

  3. Click on connect
  4. You should be able to see Movie table as below
  5. SpringBootH2MovieTable

Test the application

Step 9:
We will test this application in postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman.If you want java based client, then you can also use how to send get or post request in java.

Create movie object

  1. Launch postman
  2. Select request type as Post
  3. Set URL as http://localhost:8080/movies
  4. Go to header and put content-type=application/json as key value pair
  5. Go to Body,select raw and paste {
    “name”: “The Godfather”,
    “genre”: “Drama”
    }
  6. Click on send

SpringBootH2Post
Here is screenshot of H2 database table.
SpringBootH2MovieGodFather
Once you create on send, let’s check if we have entry in H2 database.
I have created few more movies object with below json with similar post request

{
“name”:”Inception”,
“genre”:”Action”
}{
“name”:”The Hangover”,
“genre”:”Comedy”
}{
“name”:”Forrest Gump”,
“genre”:”Comedy”
}

Here are records in database after above post requests.

Get all movie objects

  1. Launch postman
  2. Select request type as Get
  3. Set URL as http://localhost:8080/movies
  4. Click on send

SpringBootH2GetMovies

Delete movie id 3

  1. Launch postman
  2. Select request type as Delete
  3. Set URL as http://localhost:8080/movies/3
  4. Click on send

SpringH2Delete
Let’s get all the movies again after deleting movie with id 3

That’s all about Spring boot H2 database example

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *