springboot连接多个库
在Spring Boot中连接多个数据库,你可以使用Spring Data JPA或JdbcTemplate,并在application.properties或application.yml中配置不同的数据源。
以下是一个简单的例子,展示如何配置两个不同的数据源:
application.properties:
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/db_primary
spring.datasource.primary.username=root
spring.datasource.primary.password=secret
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/db_secondary
spring.datasource.secondary.username=root
spring.datasource.secondary.password=secret
spring.jpa.primary.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.secondary.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
配置类:
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "entityManagerPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
@Qualifier("primaryDataSource") DataSource dataSource) {
return entityManagerFactory(dataSource, "primary");
}
@Bean(name = "entityManagerSecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return entityManagerFactory(dataSource, "secondary");
}
private LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, String persistenceUnitName) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("your.package.for.entities");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setPersistenceUnitName(persistenceUnitName);
em.setJpaProperties(jpaProperties());
return em;
}
private Properties
评论已关闭