5

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?

0

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

Comments

3

Usually I use this in my @Config class:

@Bean
public DataSource h2TestDataSource(){
   return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}

So I use Spring Embedded DB in my spring projects (I don't use spring boot)

I hope it's useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.