How to get a reference to currently active dataSource in Spring Boot
Defining DataSource in Spring
package com.javaskool.config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "userEntityManager",
transactionManagerRef = "userTransactionManager",
basePackages = "com.javaskool.dao"
)
public class UserDBConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix = "spring.user.datasource")
public DataSource postgresqlDataSource() {
/*return DataSourceBuilder
.create()
.build();*/
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.user.datasource.driverClassName"));
dataSource.setUrl(env.getProperty("spring.user.datasource.url"));
dataSource.setUsername(env.getProperty("spring.user.datasource.username"));
dataSource.setPassword(env.getProperty("spring.user.datasource.password"));
return dataSource;
}
@Bean(name = "userEntityManager")
public LocalContainerEntityManagerFactoryBean postgresqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(postgresqlDataSource())
.properties(hibernateProperties())
.packages("com.javaskool.domain")
.persistenceUnit("js_user_PU")
.build();
}
@Bean(name = "userTransactionManager")
public PlatformTransactionManager postgresqlTransactionManager(@Qualifier("userEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
private Map hibernateProperties() {
Resource resource = new ClassPathResource("hibernate.properties");
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap();
}
}
}
Usage of DataSource
If you have a datasource already created as above it will be in the spring container, so you can call it as below
package com.javaskool.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GeneralServiceClass {
@Autowired
DataSource dataSource;
//TODO
public void cleanupDatasource() throws Exception {
Connection connection = null;
try {
connection = dataSource.getConnection();
try {
Statement stmt = connection.createStatement();
try {
stmt.execute("TRUNCATE SCHEMA PUBLIC RESTART IDENTITY AND COMMIT NO CHECK");
connection.commit();
System.out.println("Schema truncated...");
} finally {
stmt.close();
}
} catch (SQLException e) {
connection.rollback();
throw new Exception(e);
}
} catch (SQLException e) {
throw new Exception(e);
} finally {
if (connection != null) {
connection.close();
}
}
}
}
application.Properties
# Show all queries
spring.datasource.initialization-mode=always
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.user.datasource.driverClassName=com.mysql.jdbc.Driver
spring.user.datasource.url=jdbc:mysql://localhost:3306/my_db123
spring.user.datasource.username=root
spring.user.datasource.password=root@123
spring.user.datasource.driver-class-name=com.mysql.jdbc.Driver
Recent Comments