Search code examples
springh2in-memory-database

Setting up in-memory H2 database without Spring Boot


I am working on a spring 5 (Not Sprig Boot) project. I need to test my application with in-memory H2 database. I am using Spring with Java Config on maven build tool. Is there any way I can configure in-memory H2 DB?


Solution

  • You can add the DataSource bean using the EmbeddedDatabaseBuilder as follows:

    @Bean
    public DataSource dataSource(
            @Value("${datasource.dbname}") String dbname,
            @Value("${datasource.script}") String script) {
    
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .setName(dbname)
                .addScript(script)
                .build();
    }
    

    application.properties

    datasource.dbname=users
    datasource.script=classpath:resources/users.sql
    

    Also you can register h2-console servlet in the application configuration class as follows:

    @Configuration
    public class WebAppConfig implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) {
            . . .
    
            servletContext
                    .addServlet("H2Console", WebServlet.class)
                    .addMapping("/console/*");
    
            . . .
        }
    }
    

    Then you can open http://localhost:8080/console and connect to the jdbc:h2:mem:users database as follows:

    login.jsp


    See also How to enable h2-console in spring-webmvc without spring-boot?