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


import_contacts

You may also like:

Related Posts

  • 11 January

    Spring boot JDBC example

    Table of ContentsTools usedProject StructureCreate new Spring boot projectMaven configurationConfigure datasource in Application.propertiesCreate database tableCreate model classCreate Repository interface and implementationCreate service interface and implementationCreate Application classRun the applicationVerify database outputGithub Source code In this post, we will see Spring boot JDBC example. As we already know Spring boot does lot of auto configurations which […]

  • 02 January

    Spring boot devtools tutorial

    Table of ContentsOverviewJRebelIntroduction to Spring Boot DevToolsAdding Devtools to your projectSpring Boot DevTools FeaturesProperty DefaultsLoggingCachingAutomatic RestartLive ReloadGlobal SettingsRemote ApplicationsFile System WatchersConclusion In this post, we’ll be looking up what does spring has to offer for developer experience. Overview Using IDEs like Eclipse, Spring Tool Suite, Intellij Idea a typical development setup includes an application code […]

  • 22 December

    Spring Boot CrudRepository

    Table of ContentsTools usedProject Structure:Wiring up MongoDBThe Repository ClassThe Save methodThe User Entity ClassBringing the UserDao and CrudRepository togetherServiceControllerApplication classRunning the code sampleConclusionSource code In this post, we’ll be looking up how to create and use Spring Boot CrudRepository. SpringBoot CrudRepository provides sophisticated CRUD functionality for the type of entity you want to be managed.This […]

  • 10 April

    Difference between Spring and Spring boot

    Table of ContentsSpring frameworkSpring bootAdvantages of Spring BootSpring vs Spring boot In this post, we will see difference between Spring and Spring boot. If you have followed spring project over time, you might have noticed it has become increasingly complex. If you want to create a spring application, you still need to put a lot […]

  • 17 September

    Spring Boot SOAP Web service Example

    Table of ContentsTools usedProject structureAdd wsdl4j dependencyXSD file to define domainGenerate domain classes based on XSDCreate Book repository with dummy dataDefine Book service endpointDefine web service configurationRun the applicatonTest WSDL URLTest Spring soap web serviceSource code In this post, we will see how to create soap web services with Spring boot. We will create contract […]

  • 08 August

    Spring boot profiles example

    Table of ContentsNeed for profilesProfiles for environment specific propertiesSetting active profileSpring boot @Profile annotationProject StructureSource code In this tutorial, we will see about Spring boot profiles. Need for profiles Application development is complex process. You might have different environment for application development. Dev SIT QA Prod We require different configuration based on the environment. For […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.