修改配置文件
spring:
application:
name: cms
primaryDataSource:
dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
url:jdbc:mysql://localhost:3306/srbairun?useUnicode=true&characterEncoding=utf-8
username: 123
password: 123
poolName: StringBootHikariCP
maximumPoolSize: 10
minimumIdle: 3
maxLifetime: 2000000
connectionTimeout: 30000
idleTimeout: 30000
pool-prepared-statements: true
max-open-prepared-statements: 300
secondaryDatasource:
dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
url: jdbc:mysql://localhost:5866/test?useUnicode=true&characterEncoding=utf-8
username: 123
password: 123
poolName: StringBootHikariCP
maximumPoolSize: 10
minimumIdle: 3
maxLifetime: 2000000
connectionTimeout: 30000
idleTimeout: 30000
pool-prepared-statements: true
max-open-prepared-statements: 300
增加数据源配置
主数据源配置:
/**
* 数据源设置
* @author rongxj
*
*/
@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages={"com.ido85","com.ido85.bairun.master","com.ido85.frame","com.ido85.sso.security"})
public class PrimaryDataSourceConfiguration {
@Value("${spring.primaryDataSource.username}")
private String user;
@Value("${spring.primaryDataSource.password}")
private String password;
@Value("${spring.primaryDataSource.url}")
private String dataSourceUrl;
@Value("${spring.primaryDataSource.dataSourceClassName}")
private String dataSourceClassName;
@Value("${spring.primaryDataSource.poolName}")
private String poolName;
@Value("${spring.primaryDataSource.connectionTimeout}")
private int connectionTimeout;
@Value("${spring.primaryDataSource.maxLifetime}")
private int maxLifetime;
@Value("${spring.primaryDataSource.maximumPoolSize}")
private int maximumPoolSize;
@Value("${spring.primaryDataSource.minimumIdle}")
private int minimumIdle;
@Value("${spring.primaryDataSource.idleTimeout}")
private int idleTimeout;
@Value("${spring.primaryDataSource.sqlScriptEncoding}")
private String encode;
@Value("${spring.jpa.multitenant.default-id}")
private String defaultTenantId;
@Value("${spring.primaryDataSource.connectionInitSqls}")
private String connectionInitSqls;
@Bean
@Primary
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.put("url", dataSourceUrl);
dsProps.put("user", user);
dsProps.put("password", password);
dsProps.put("prepStmtCacheSize", 250);
dsProps.put("prepStmtCacheSqlLimit", 2048);
dsProps.put("cachePrepStmts", Boolean.TRUE);
dsProps.put("useServerPrepStmts", Boolean.TRUE);
Properties configProps = new Properties();
configProps.put("dataSourceClassName", dataSourceClassName);
configProps.put("poolName", poolName);
configProps.put("maximumPoolSize", maximumPoolSize);
configProps.put("minimumIdle", minimumIdle);
configProps.put("minimumIdle", minimumIdle);
configProps.put("connectionTimeout", connectionTimeout);
configProps.put("idleTimeout", idleTimeout);
configProps.put("dataSourceProperties", dsProps);
configProps.put("connectionInitSql", connectionInitSqls);
HikariConfig hc = new HikariConfig(configProps);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
@Bean(name="entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(DataSource dataSource, JpaProperties jpaProperties) {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
// jpaProperties.getProperties().put("hibernate." + "ejb.naming_strategy_delegator", "none");
factory.setJpaPropertyMap(jpaProperties.getProperties());
factory.setPackagesToScan("com.ido85");
factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
factory.setPersistenceUnitName("system");
factory.afterPropertiesSet();
return factory;
}
@Bean(name = "transactionManagerPrimary")
@DependsOn("entityManagerFactoryPrimary")
@Primary
PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactoryPrimary") LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary) {
return new JpaTransactionManager(entityManagerFactoryPrimary.getObject());
}
@Bean(name = "idGenerator")
IdGenerator idGenerator() {
return new DistributedIdGenerator(1l);
}
}
副数据源配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = "com.ido85.bairun.msg")
public class SecondaryDataSourceConfiguration {
@Value("${spring.secondaryDatasource.username}")
private String user;
@Value("${spring.secondaryDatasource.password}")
private String password;
@Value("${spring.secondaryDatasource.url}")
private String dataSourceUrl;
@Value("${spring.secondaryDatasource.dataSourceClassName}")
private String dataSourceClassName;
@Value("${spring.secondaryDatasource.poolName}")
private String poolName;
@Value("${spring.secondaryDatasource.connectionTimeout}")
private int connectionTimeout;
@Value("${spring.secondaryDatasource.maxLifetime}")
private int maxLifetime;
@Value("${spring.secondaryDatasource.maximumPoolSize}")
private int maximumPoolSize;
@Value("${spring.secondaryDatasource.minimumIdle}")
private int minimumIdle;
@Value("${spring.secondaryDatasource.idleTimeout}")
private int idleTimeout;
@Value("${spring.jpa.multitenant.default-id}")
private String defaultTenantId;
@Value("${spring.primaryDataSource.connectionInitSqls}")
private String connectionInitSqls;
@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
Properties dsProps = new Properties();
dsProps.put("url", dataSourceUrl);
dsProps.put("user", user);
dsProps.put("password", password);
dsProps.put("prepStmtCacheSize", 250);
dsProps.put("prepStmtCacheSqlLimit", 2048);
dsProps.put("cachePrepStmts", Boolean.TRUE);
dsProps.put("useServerPrepStmts", Boolean.TRUE);
Properties configProps = new Properties();
configProps.put("dataSourceClassName", dataSourceClassName);
configProps.put("poolName", poolName);
configProps.put("maximumPoolSize", maximumPoolSize);
configProps.put("minimumIdle", minimumIdle);
configProps.put("minimumIdle", minimumIdle);
configProps.put("connectionTimeout", connectionTimeout);
configProps.put("idleTimeout", idleTimeout);
configProps.put("dataSourceProperties", dsProps);
configProps.put("connectionInitSql", connectionInitSqls);
HikariConfig hc = new HikariConfig(configProps);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
@Qualifier("secondaryDataSource") DataSource dataSource,
JpaProperties jpaProperties) {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
factory.setJpaVendorAdapter(jpaVendorAdapter());
// jpaProperties.getProperties().put("hibernate.dialect",
// "org.hibernate.dialect.MySQLDialect");
// jpaProperties.getProperties().put("hibernate.multiTenancy",
// hibernateMultiTenancy);
// jpaProperties.getProperties().put(
// "hibernate.tenant_identifier_resolver",
// tenant_identifier_resolver);
// jpaProperties.getProperties().put(
// "hibernate.multi_tenant_connection_provider",
// multi_tenant_connection_provider);
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
// properties.put(org.hibernate.cfg.Environment.MULTI_TENANT,
// MultiTenancyStrategy.SCHEMA);
// properties.put(org.hibernate.cfg.Environment.MULTI_TENANT_CONNECTION_PROVIDER,
// multiTenantConnectionProvider);
// properties.put(org.hibernate.cfg.Environment.MULTI_TENANT_IDENTIFIER_RESOLVER,
// tenantIdentifierResolver);
// properties.put(org.hibernate.cfg.Environment.IMPLICIT_NAMING_STRATEGY, "legacy-jpa");
// properties.put(org.hibernate.cfg.Environment.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategyStandardImpl.INSTANCE);
// properties.put(org.hibernate.cfg.Environment.DEFAULT_SCHEMA,
// defaultTenant);
properties.put(org.hibernate.cfg.Environment.GENERATE_STATISTICS,
false);
factory.setJpaPropertyMap(properties);
factory.setPackagesToScan("com.ido85.bairun.msg");
factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
factory.setPersistenceUnitName("msg");
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
factory.afterPropertiesSet();
factory.setJpaVendorAdapter(jpaVendorAdapter());
return factory;
}
@Bean(name = "transactionManagerSecondary")
@DependsOn("entityManagerFactorySecondary")
PlatformTransactionManager transactionManagerSecondary(
@Qualifier("entityManagerFactorySecondary") LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory) {
return new JpaTransactionManager(
secondaryEntityManagerFactory.getObject());
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
// jpaVendorAdapter.setGenerateDdl(true);
return jpaVendorAdapter;
// return new HibernateJpaVendorAdapter();
}
}
注意@Primary注解的添加。
使用方式
1.在上面basePackages 配置的扫描路径下的实体类,jpa资源类自动寻找对应的数据源。
2.如果使用EntityManager方法的话,@PersistenceContext(unitName = "msg")指定使用那个数据源,unitName是在上面数据源配置模块配置好的。
Springboot+jpa多数据源
最新推荐文章于 2024-09-12 08:20:11 发布