In this tutorial, I will show you how to add support for the H2 in-memory database to your Spring Boot project with Spring Security enabled. By the end of this tutorial, you will be able to watch a video demonstration of how to implement it.
After following the steps below, your Spring Boot project will be configured to use the H2 in-memory database. Any data written to this database will be stored in memory, which means that if you restart or shut down your Spring Boot application, any data stored in the in-memory database tables will be lost.
Add H2 In-Memory Database POM.xml Dependency
Open the POM.xml file of your Spring Boot project and add the following dependency:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
Update the application.properties File
To use the H2 in-memory database console and view the content of its tables, enable the h2-console in your application.properties file.
Add the following lines to the application.properties file:
spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Configure HttpSecurity
Disable the frameOptions()
If your Spring Boot project uses Spring Security, you probably have a class that is annotated with @EnableWebSecurity annotation. To disable the HTTP Header Frame Options, add the following to the configure() method of that class. Frame options are necessary to prevent a browser from loading your HTML page in an <iframe> or <frame> tag. To enable the H2 Console page to load, you need to disable this option.
http.headers().frameOptions().disable();
Allow access to /h2-console URL path
To access the H2 in-memory database console, you will also need to allow access to the /h2-console path. This can be done by adding the following code snippet to your HttpSecurity configuration:
requestMatchers(new AntPathRequestMatcher("/h2-console/**")) .permitAll()
Here is my complete configure()
function, which configures the HttpSecurity
. Note that I granted access to the /h2-console
URL.
@Bean protected SecurityFilterChain configure(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()); http.authorizeHttpRequests(authz -> authz .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll() .anyRequest().authenticated()) .addFilter(new AuthenticationFilter(authenticationManager())) .addFilter(new AuthorizationFilter(authenticationManager())) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.headers().frameOptions().disable(); return http.build(); }
Now, you should be able to do the following:
- Build and Run your Spring Boot application
- Open the URL http://localhost:8080/<application context>/h2-console in your browser window. Note that you should only include the <application context> if you have set it in your application.properties file, like this:
server.servlet.context-path=/MyProjectName
If you have not set an application context, leave out this part of the URL.
H2 Console Login page
After completing the above steps, you should see the following login page:
To start working with the H2 in-memory database, click on ‘Connect’ to sign in to your H2 Console.
Database “mem:testdb” not found, either pre-create it or allow remote database creation
If you encounter the error message ‘Database “mem:testdb” not found, either pre-create it or allow remote database creation’ while attempting to log in, you need to configure the H2 database access details in the application.properties file.
spring.h2.console.enabled=true spring.datasource.username=sergey spring.datasource.password=sergey spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
This should resolve the issue.
Video Demonstration
You can find more videos here: RESTful Web Services, Java, Spring Boot, Spring MVC and JPA
If you’re interested in further learning about Spring Boot, we recommend checking out the video courses listed above. Hopefully, one of them will be useful to you.
Frequently asked questions
- How is H2 database different from other relational databases?
H2 database is an in-memory database that is commonly used for testing and development purposes. It is lightweight, fast, and has a small footprint, making it easy to set up and use in a variety of contexts. Unlike traditional relational databases like MySQL or PostgreSQL, H2 database is designed to be embedded within a Java application, which can make it more convenient for certain use cases. - Can I use H2 database in production environments?
While H2 database is primarily intended for testing and development purposes, it is possible to use it in production environments as well. However, it’s important to understand that H2 database may not be as robust or feature-rich as other relational databases, and it may not be as well-suited for handling large-scale or complex data sets. Additionally, H2 database is an in-memory database, which means that data may be lost if the application crashes or the server is shut down. - How can I migrate data from H2 database to another database?
If you decide to switch from H2 database to another database for production use, you will need to migrate your data to the new database. There are several tools and frameworks available for migrating data between databases, including Apache Camel, Flyway, and Liquibase. Additionally, you can use Java Persistence API (JPA) to map H2 database entities to entities in the new database and transfer the data using JPA. - How do I debug issues with H2 database in my Spring Boot application?
If you encounter issues with H2 database in your Spring Boot application, there are several steps you can take to debug the problem. First, check the H2 database console output for error messages or warnings. You can also use the Spring Boot Actuator to monitor the status of the database connection and other metrics. Additionally, you can enable verbose logging for the H2 database and Spring Boot to get more detailed information about what’s happening behind the scenes. Finally, consider reaching out to the Spring Boot or H2 database communities for help or guidance.