Image Image

This guide will help you understand the concept of in retentiveness database. We will expect at uncomplicated JPA case to understand the best practices in using in memory databases.

You volition learn

  • What is an in memory database?
  • Why do you employ an in memory database?
  • What are the best practices in using an in memory database?
  • How to connect a Spring Kicking projection to H2?

Free Courses - Learn in 10 Steps

  • Free 5 DAY Claiming - Learn Bound and Jump Boot
  • Learn Spring Boot in 10 Steps
  • Larn Docker in 10 Steps
  • Learn Kubernetes in x Steps
  • Learn AWS in 10 Steps

What is an in memory database?

Typical databases involve a lot of setup.

For example, with Oracle or mySQL databases, you lot would demand to

  • Install the Database
  • Setup a Schema
  • Setup the tables
  • Populate the information
  • Connect the application to the database by setting up a data source and a lot of other code

Scenario 1 - Let's consider a situation where you would want to do a quick POC. Using a traditional database involves a lot of overhead.

Scenario two - Consider your unit tests

  • You don't want them to fail when some data/schema in the database changes
  • You would want to be able to run them in parallel - multiple developers might exist running the tests in parallel.

In these kind of scenarios, an in memory database provides an ideal solution.

An in memory database is created when an awarding starts up and destroyed when the awarding is stopped.

Advantages

  • Aught projection setup or infrastructure
  • Zero Configuration
  • Zero Maintainance
  • Like shooting fish in a barrel to utilise for Learning, POCs and Unit Tests
  • Bound Kicking provides Simple Configuration to switch between a real database and an in retentiveness database similar H2

H2

H2 is one of the popular in memory databases. Spring Kick has very good integration for H2.

From https://en.wikipedia.org/wiki/H2_(DBMS)

H2 is a relational database management arrangement written in Java. It can be embedded in Java applications or run in the client-server fashion.

H2 supports a sub set of the SQL standard.

H2 also provides a web panel to maintain the database.

Leap Boot and H2

You need very picayune configuration to connect Spring Boot application with H2.

In most situations, merely calculation the H2 runtime jar into dependencies should be sufficient.

            <dependency>     <groupId>com.h2database</groupId>     <artifactId>h2</artifactId>     <scope>runtime</scope> </dependency>                      

Setting up a Jump Boot Project with H2

Spring Initializr http://start.spring.io/ is great tool to bootstrap your Leap Boot projects.

Image

Every bit shown in the image higher up, following steps have to be done

  • Launch Spring Initializr and choose the post-obit
    • Choose com.in28minutes.springboot.rest.example as Grouping
    • Choose spring-boot-ii-jpa-with-hide-and-h2 every bit Artifact
    • Choose following dependencies
      • Web
      • JPA
      • H2
      • DevTools
  • Click Generate Projection.
  • Import the projection into Eclipse. File -> Import -> Existing Maven Project.

Ensure that H2 is selected in the dependencies.

Create a simple Student Entity with a primary key id.

                          @Entity              public              class              Student              {              @Id              @GeneratedValue              private              Long              id              ;              private              String              proper name              ;              private              Cord              passportNumber              ;                      

H2 - A Few Tips

  • An in-memory database is live only during the time of execution of the application. It is an efficient style to learn a framework.
  • This is not how you desire your existent world applications to behave.
  • We explain how to connect to a database of your choice in the reply to the question "How practice we connect to a external database?".

Image Image Image

Image

Image


Spring Boot and H2 Magic

H2 provides a spider web interface chosen H2 Panel to see the data. Let's enable h2 console in the awarding.backdrop.

/src/chief/resources/application.properties

                          # Enabling H2 Console                            spring.h2.console.enabled              =              true              spring.datasource.url              =              jdbc:h2:mem:testdb              bound.data.jpa.repositories.bootstrap-mode              =              default                      

When you get-go the application up now, you would see a lot of magic unfold!

When y'all reload the application, yous tin launch upwards H2 Console at http://localhost:8080/h2-panel.

Image

Tip - Make sure that you use jdbc:h2:mem:testdb as JDBC URL.

You lot volition see that a new table called 'student' is created in H2 Console.

How did the Student table get created?

Its because of Bound Boot Car Configuration. We volition talk near this in the next section.

You tin can also populate some information into pupil tabular array by adding a file called data.sql

/src/main/resource/information.sql

            insert into pupil values(10001,'Ranga', 'E1234567');  insert into educatee values(10002,'Ravi', 'A1234568');                      

When you reload the application, y'all tin launch up H2 Console to see that the student table is populated with the data from `data.sql'

  • http://localhost:8080/h2-panel.

How did all the magic happen? Let'due south expect at information technology question past question in the adjacent section.

Oft asked questions most Spring Boot, JPA, Hibernate and H2

Q : How does H2 and Spring Boot combination work?

Offset and most important thing - Spring Kick is intelligent.

If you are talking to an in memory db, by default, information technology looks at the entities and creates the database and the tables.

However, if you connect to a mysql database, Bound Kick knows that its a permanent database. By default, it expects you to set upward the database, set the tables and it uses the connectedness that you established.

Q : How did the Spring Boot Application connect to the database H2?

Its downwards to Spring Boot Auto Configuration!

Outset thing yous would demand to understand is Leap Kick Auto Configuration.

Here's a good read

  • http://www.springboottutorial.com/spring-kicking-machine-configuration

Every bit far as H2 is concerned, equally shortly as Bound Boot sees H2 in the class path, information technology motorcar configures a data source similar to what you run across below:

            spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Commuter spring.datasource.username=sa bound.datasource.countersign=  spring.jpa.database-platform=org.hide.dialect.H2Dialect                      

It knows that you are using an in-retentivity database H2 and it uses the default url if you don't provide one.

Q : Where is the database connectedness info specified? How does it know to automatically connect to H2?

Thats Jump Boot Motorcar-configuration magic.

From https://docs.spring.io/spring-boot/docs/electric current/reference/html/using-kick-auto-configuration.html

Spring Kick machine-configuration attempts to automatically configure your Spring application based on the jar dependencies that y'all accept added. For case, If HSQLDB is on your classpath, and you take not manually configured whatsoever database connection beans, so Spring Boot will auto-configure an in-memory database.

Recommended Reading

  • http://www.springboottutorial.com/spring-kicking-motorcar-configuration

Q : What happens if H2 is non in the classpath?

You get this error

            Cannot make up one's mind embedded database commuter class for database type NONE                      

Add H2 to the pom.xml and Restart your server

            <dependency> 	<groupId>com.h2database</groupId> 	<artifactId>h2</artifactId> 	<scope>runtime</scope> </dependency>                      

Q : Why is the data lost betwixt restart?

H2 is an in memory database. Its not a persisted database.

H2 is a bang-up tool for learning because yous need zero setup.

Fault : Tabular array is not created automatically in H2 embedded db or I'm unable to see the tables

Usually, the table's are created but the URL used in H2 GUI Console is wrong.

In the browser, change the database URL to jdbc:h2:mem:testdb (Shown in the screen below).

Y'all should be expert to go!

Error : H2 Panel is non Launched up?

Try enabling it in the application.backdrop

            spring.h2.console.enabled=true                      

Q : How did the insert query from data.sql run at application startup?

That'due south part of the Leap Boot startup routine. Whatsoever queries in data.sql are run at awarding startup. You can read more here.

  • https://docs.bound.io/leap-boot/docs/current/reference/html/howto-database-initialization.html

Running H2 as a persisted database with Spring Kick

While we dont recommend this , it interesting to annotation that H2 has a persisted database mode

  • With this configuration, the data is not lost fifty-fifty afterwards spring boot restart and reckoner restart.

You would detect H2 being very rarely used in this fashion. If you are really interested in a persistent database, we recommend exploring MySQL, Oracle or some other relational database.

application.backdrop

            spring.datasource.proper name=yourdbname spring.datasource.driverClassName=org.h2.Commuter   bound.datasource.initialize=false spring.datasource.url=jdbc:h2:file:~/yourdbname;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=True;DB_CLOSE_DELAY=-ane;   spring.jpa.hibernate.ddl-auto = update                      

Using H2 for unit tests

The standard properties file that Spring Kick picks up automatically when running an awarding is called application.properties and resides in the src/main/resources binder.

If nosotros want to use dissimilar properties for tests, and so we tin can override the properties file in the main binder past placing some other file with the aforementioned name in src/test/resource.

The awarding.properties file in src/test/resource binder should contain the standard fundamental-value pairs necessary for configuring a in retentiveness connection.

Start add together the dependencies for your database driver (mysql in the instance below) and make the dependency for h2 test scoped.

            <dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId> </dependency>  <dependency>     <groupId>com.h2database</groupId>     <artifactId>h2</artifactId>     <scope>examination</telescopic> </dependency>                      

Use the mysql database for your real code

src\main\resources\application.properties

            spring.jpa.hibernate.ddl-motorcar=none bound.datasource.url=jdbc:mysql://localhost:3306/person_example spring.datasource.username=personuser bound.datasource.password=YOUR_PASSWORD                      

Use in memory database for your unit of measurement tests

src\test\resources\application.properties

            leap.datasource.driver-course-name=org.h2.Driver jump.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 spring.datasource.username=sa jump.datasource.password=sa