SATURN  RING  STATION

At a distant space view post, we chat about codes.

Spring Data JPA excludes database in certain environment/profile.

In some scenario, we just don’t need the database at all, but Spring Data JPA gets error at start up complaining no DB connection.

We can exclude the database connection classes from being created. Then include them back when needed.

First we exclude them from Spring Boot auto-configuration.

@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
		HibernateJpaAutoConfiguration.class,
		DataSourceTransactionManagerAutoConfiguration.class })
@Configuration
@ComponentScan(basePackages = { "com.yourapp" })
public class yourApplication {
	public static void main(String[] args) {
		SpringApplication.run(yourApplication.class, args);
	}
}

By including, I means we reconfigure Spring Data JPA, when a DB is needed in certain environment/profile.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.yourapp.service")
@Profile("Production")
public class DataScourceConfig {

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder
                .create()
                .url(env.getProperty("spring.datasource.url"))
                .username(env.getProperty("spring.datasource.username"))
                .password(env.getProperty("spring.datasource.password"))
                .driverClassName("org.postgresql.Driver")
                .build();
    }

    @Bean
    public PlatformTransactionManager transactionManager()
    {
        EntityManagerFactory factory = entityManagerFactory().getObject();
        return new JpaTransactionManager(factory);
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator()
    {
        return new HibernateExceptionTranslator();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        vendorAdapter.setGenerateDdl(Boolean.TRUE);

        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan("com.yourapp");

        factoryBean.setJpaVendorAdapter(vendorAdapter);
        factoryBean.setJpaProperties(additionalProperties());

        return factoryBean;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        return properties;
    }
}

 

Btw this whole app is on GitHub, in CrawlerWithDB folder.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Spring Data JPA excludes database in certain environment/profile.