Introduction
Basically, database setup involves several steps before it can be used in an application through a configured data source. In actual project implementation, this is actually required. However, in some cases we just need a POC done for certain things, and the whole database setup work is still a must. Also for unit testing it would be ideal to have our own recordset in the database so that it is independent from data changes in the deployment environment. For such use cases, an in-memory database is the ideal solution.
In-memory databases are created when the application starts, and databases are destroyed when the application stops.
Spring Boot easily integrates with the H2 database. So you can easily and quickly switch between real and in-memory databases.
Note that the H2 InMemory database is a relational DBMS written in Java.
Let’s take a quick demo.
Implementation
Let’s generate a Spring Boot project from Spring initializr. Make sure to add Web, JPA, H2 and DevTools dependencies as shown below.
Let’s take a look at the generated pom file.
pom.xml
4.0.0
com.jcombat
h2demo
0.0.1-SNAPSHOT
jar
h2demo
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.1.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
We also noticed that the application.properties file was generated as –
application.properties
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
#Datasource
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
The property spring.h2.console.enabled=true enables the web console at http://localhost:8080/h2
Click Connect and you will be taken to a page where you can see the available tables in the database.
You may be wondering, how to create the Student table. The magic is that data.sql is located in src/main/resources. Just make sure you have insert statements in your data.sql file as described below –
data.sql
insert into STUDENT
values(10001,'Ajay','AAA1');
insert into STUDENT
values(10002,'Ajit','AAA2');
Spring Boot auto-configuration checks the values in the data.sql file and does what is necessary for you, i.e. creates the STUDENT table and executes the insert statement. clever!
Let’s examine what to do with these student records.
For this, let us now create the Student entity class.
Student.java
package com.jcombat.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue
private Long id;
private String name;
private String section;
public Student() {
}
public Student(Long id, String name, String section) {
this.id = id;
this.name = name;
this.section = section;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
To access the database, let’s write a simple JPA interface that provides the helper functions needed to perform basic DB operations.
StudentRepository. java
package com.jcombat.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.jcombat.entity.Student;
@Repository
public interface StudentRepository extends JpaRepository {
}
Now let’s customize the Spring Boot entry point class with the Command Line Runner so that we can execute the Spring Boot application from the command line.
package com.jcombat.h2demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.jcombat.repository.StudentRepository;
@SpringBootApplication
@EntityScan("com. jcombat. entity")
@EnableJpaRepositories("com.jcombat.repository")
public class H2demoApplication implements CommandLineRunner {
// mvn spring-boot:run
private Logger LOG = LoggerFactory. getLogger("H2demoApplication");
StudentRepository studentRepository;
@Autowired
public H2demoApplication(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public static void main(String[] args) {
SpringApplication.run(H2demoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
LOG.info("Student count in DB: {}", studentRepository.count());
}
}
Execute application
To run the application, you can do it directly from the Eclipse IDE or from the command line with the following command –
mvn spring-boot:run
Once executed, we see the following output on the console –
Download source code
Translated from: https://www.javacodegeeks.com/2018/11/ understand-in-memory-database-spring.html
vYWRzLzIwMTgvMTEvYnV0dG9uLTQucG5n?x-oss-process=image/format,png” alt=”H2 memory database” width=”316″ height=”49″>
Translated from: https://www.javacodegeeks.com/2018/11/ understand-in-memory-database-spring.html