![](/img/trans.png)
[英]Spring Boot change DataSource and JPA properties at runtime
[英]Change datasource properties for JPA Spring Configuration during runtime
我正在开发一个需要连接到多个数据库的 Spring 项目。
我使用的示例都是使用在应用程序开始时设置的属性连接到一个数据库。
我当前的 JPA 配置如下所示:
@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig{
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.google.persistence.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
dataSource.setUsername( "user" );
dataSource.setPassword( "password" );
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
}
在这种情况下,已经设置了数据源属性(驱动程序、url、用户名、密码)。 但是是否可以修改这个当前的 bean 或创建一个允许我在运行时修改这些属性的新方法?
例如,在应用程序运行时,我是否可以手动断开与当前数据库的连接,修改数据源属性,然后重新连接到新数据库?
您无法在运行时中更改此属性,但是如果需要使用多个数据库,则可以创建多个持久性单元。 在这里您可以找到示例:
您正在寻找的功能称为多租户。
例如,请参阅本指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.