This tutorial explains about using H2 database in spring boot application with hibernate as a JPA provider. We will also take a look into accessing H2 db console in spring boot along with spring security integration.Here we will be creating a spring boot H2 database example app which will have REST endpoints exposed and perform some db operations.

Why H2 database and Spring Boot

Using H2 database is fast, open source and provides JDBC API to connect to java applications. It is very convenient to use and provides browser based console. H2 database is mostly used as in-memory database and Spring boot provides out of the box support for H2. Spring Boot can auto-configure embedded H2 database meaning you dont need to provide any H2 specific configurations in your spring boot application. Include the required dependencies and spring boot will take care of other things.

The example shown here is primarily meant to use H2 database during development phase as it is light, fast and easy to use and provides convenient way to emulate other DBs which we use in production environment.

H2 and spring boot Maven Dependencies

Since we want to have a H2 console, the scope is not defined as runtime and hence by default it is compile time.

spring-boot-starter-parent : It provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies.

spring-boot-starter-web : It includes all the dependencies required to create a web app. This will avoid lining up different spring common project versions.

spring-boot-starter-tomcat : It enable an embedded Apache Tomcat 7 instance, by default.This can be also marked as provided if you wish to deploy the war to any other standalone tomcat.

spring-boot-starter-data-jpa : It provides key dependencies for Hibernate, Spring Data JPA and Spring ORM.

<parent> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-parent </artifactId> <version> 1.5.1.RELEASE </version> </parent> <dependencies> <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-web </artifactId> </dependency> <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-tomcat </artifactId> </dependency> <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-data-jpa </artifactId> <exclusions> <exclusion> <groupId> org.apache.tomcat </groupId> <artifactId> tomcat-jdbc </artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId> com.h2database </groupId> <artifactId> h2 </artifactId> //<scope>runtime</scope> </dependency> </dependencies>

Defining Spring Boot Application class

@SpringBootApplication enables many defaults.It is a convenience annotation that adds @Configuration, @EnableAutoConfiguration, @EnableWebMvc, @ComponentScan

The main() method uses Spring Boot SpringApplication.run() method to launch an application.

package com.devglan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } }

H2 database configuration in Spring Boot

The important thing to note here is the url. DB_CLOSE_ON_EXIT=FALSE disables the database automatic shutdown and Spring Boot will ensure to close it once access to the database is no longer needed.

spring.datasource.url= jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username= sa spring.datasource.password= spring.datasource.driverClassName= org.h2.Driver spring.jpa.hibernate.ddl-auto= update spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.H2Dialect

Hibernate Entity Class

Following is the entity class. The class is annotated as hibernate entity.

package com.devglan.model; @Entity @Table public class UserDetails { @Id @Column @GeneratedValue (strategy = GenerationType.IDENTITY) private int id; @Column private String firstName ; @Column private String lastName ; @Column private String email ; @Column private String password ; //getters and setters goes here

Defining Spring Boot Controller

Let us define our controller. It has one url mapping that intercepts request at /list and returns all users present in db.

package com.devglan.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.devglan.model.UserDetails; import com.devglan.service.UserService; @Controller public class UserController { @Autowired private UserService userService; @RequestMapping (value = "/list" , method = RequestMethod. GET ) public ResponseEntity > userDetails() { List userDetails = userService.getUserDetails(); return new ResponseEntity >(userDetails, HttpStatus. OK ); } }

Defining Service Class

package com.devglan.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.devglan.dao.UserDao; import com.devglan.model.UserDetails; import com.devglan.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public List getUserDetails() { return userDao. getUserDetails(); } }

Defining Dao Implementation

Let us define the dao. Here we are free to choose JPA entitymanager to perform db operations or use hibernate session as shown below:

package com.devglan.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.hibernate.Criteria; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.devglan.dao.UserDao; import com.devglan.model.UserDetails; @Repository public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager entityManager; public List getUserDetails() { Criteria criteria = entityManager.unwrap(Session. class ).createCriteria(UserDetails. class ); return criteria.list(); } }

H2 database Console Configuration

Following is the configuration to view the H2 database console in the path /console. It declares the servlet wrapper for the H2 database console /console . Here we have imported WebServlet class that is from H2.

package com.devglan; import org.h2.server.web.WebServlet; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BeanConfig { @Bean ServletRegistrationBean h2servletRegistration(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet()); registrationBean.addUrlMappings( "/console/*" ); return registrationBean; } }

SQL

Following are some sample DML. We will be creating some dummy user details using following insert statements.

create table User_Details (id integer not null auto_increment, email varchar(255), first_Name varchar(255), last_Name varchar(255), password varchar(255), primary key (id)); INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin'); INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('john@gmail.com','john','doe','johndoe'); INSERT INTO user_details(email,first_Name,last_Name,password) VALUES ('sham@yahoo.com','sham','tis','shamtis');

Accessing H2 Database Console

Hit the url - localhost:8080/console and you can see folowing screen.

Click on connect button and you will be forwarded to /console page

Now run above sqls

And try to access localhost:8080/list and you will see below screen.

Adding Spring Security to H2 Datbase Console

Add following maven dependencies to the pom file. Once this dependency is added, Spring Boot will not allow the access of /console without default basic authentication.

One thing you can do is use default username/password provided by spring boot security to access the /console page. The default username is user and default password is logged by spring boot in the console.

<dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-security </artifactId> </dependency>

You can also define your custom security configurations or remove the authentication for /console as below:

package com.devglan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable().authorizeRequests().antMatchers( "/" ).permitAll().and().authorizeRequests() .antMatchers( "/console/**" ).permitAll(); .antMatchers( "/list/**" ).permitAll(); httpSecurity.headers().frameOptions().disable(); } }

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download source