Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure h2 for spring boot

Tags:

spring-boot

h2

I'm trying to configure spring boot to set my test datasource to use h2 in postgresql mode. I set these lines in my test/resources/application:

spring.datasource.url=jdbc:h2:mem:db1;MODE=PostgreSQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

But spring boot keep loading me default h2 configuration.

How can I force spring boot to use my special h2 configuration ?

like image 937
user2854544 Avatar asked Jan 30 '15 10:01

user2854544


People also ask

Do we need to install H2 database for spring boot?

No configuration − Spring Boot intrinsically supports H2 and no extra configuration required to configure H2 database. Easy to Use − H2 Database is very easy to use. Lightweight and Fast − H2 database is very lightweight and being in memory, it is very fast.

How does spring boot automatically connects to H2 database?

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot will auto-configure an in-memory database.


1 Answers

just do it in java-configuration like this:

    @Configuration
@EnableAutoConfiguration
@Profile({ "dev", "demo" })
public class EmbeddedDatabaseConfiguration {
    @Bean(name = "dataSource")
    public DriverManagerDataSource getDataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("org.h2.Driver");
        driverManagerDataSource.setUrl("jdbc:h2:mem:mylivedata;IGNORECASE=TRUE;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1");
        return driverManagerDataSource;
    }
}
like image 149
lubo08 Avatar answered Oct 28 '22 04:10

lubo08