In fact, it is not difficult to configure spring boot jap+mybatis druid with multiple data sources
The key cannot be confused. Otherwise, after the configuration is completed, the connection of the druid data source may explode some strange errors, such as connection timeout, connection unavailable, etc
Reference resources:
Create a DataSourceConfig configuration class to define the data source. In fact, @ Primary means the default. If JPA is used, the data source is used by default.
Reference https://blog.csdn.net/qq_27470131/article/details/79558970
It's just like this. It's not complicated.
Reference: https://www.cnblogs.com/falcon-fei/p/11060085.html
Here is my configuration:
package com.newpearl.da.service.config; import com.alibaba.druid.filter.config.ConfigTools; import com.alibaba.druid.pool.DruidDataSource; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.sql.SQLException; /** * DruidDBConfig Class is marked with @ Configuration as Configuration information; * DataSource Object is declared by @ Bean and managed by Spring container, * @Primary Indicates that the DataSource defined here will overwrite the DataSource of other sources. * @author xiaocheng *jdbc.url=${jdbc.url} *The latest support methods are as follows: *jdbc.url=@jdbc.url@ */ @Configuration public class DruidDBConfig { private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class); @Value("${spring.datasource.url}") private String dbUrl; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.publicKey}") private String publicKey; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.initialSize}") private int initialSize; @Value("${spring.datasource.minIdle}") private int minIdle; @Value("${spring.datasource.maxActive}") private int maxActive; @Value("${spring.datasource.maxWait}") private int maxWait; @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.validationQuery}") private String validationQuery; @Value("${spring.datasource.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.testOnReturn}") private boolean testOnReturn; @Value("${spring.datasource.poolPreparedStatements}") private boolean poolPreparedStatements; @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}") private String filters; @Value("{spring.datasource.connectionProperties}") private String connectionProperties; @Bean(name = "primaryDataSource") @Qualifier("primaryDataSource") @Primary //Configure this data source as the primary data source public DataSource primaryDataSource(){ // return DataSourceBuilder.create().build(); logger.info("==== Start configuration of master data source"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(username); datasource.setPassword(passwordDecode()); datasource.setDriverClassName(driverClassName); // configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (SQLException e) { } datasource.setConnectionProperties(connectionProperties); // datasource.setKeepAlive(true); // // datasource.setRemoveAbandoned(true); ///// / unit second // datasource.setRemoveAbandonedTimeout(300); // datasource.setLogAbandoned(true); // datasource.setMaxEvictableIdleTimeMillis(360000); return datasource; } @Bean(name = "analysisDataSource") @Qualifier("analysisDataSource") // @ConfigurationProperties(prefix = "spring.datasource.analysis") public DataSource analysisDataSource(){ // return DataSourceBuilder.create().build(); logger.info("==== Start configuring data source"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(username); datasource.setPassword(passwordDecode()); datasource.setDriverClassName(driverClassName); // configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (SQLException e) { } datasource.setConnectionProperties(connectionProperties); datasource.setKeepAlive(true); // datasource.setRemoveAbandoned(true); // / / unit seconds // datasource.setRemoveAbandonedTimeout(300); // datasource.setLogAbandoned(true); datasource.setMaxEvictableIdleTimeMillis(360000); return datasource; } private String passwordDecode() { String passwordDecode = null; try { if (StringUtils.isNotEmpty(this.publicKey)) { passwordDecode = ConfigTools.decrypt(this.publicKey, this.password); } } catch (Exception e) { e.printStackTrace(); } return passwordDecode; } }
From the mybatis data source:
package com.newpearl.da.service.config; import org.apache.ibatis.session.SqlSessionFactory; import org.hibernate.cfg.ImprovedNamingStrategy; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; /** * @author tanjiayao * @Description * @date 2018-10-22 */ @Configuration @EnableTransactionManagement @MapperScan(basePackages = {"com.newpearl.da.biz.mapper"}, sqlSessionTemplateRef = "sqlSessionTemplateAnalysis") public class AnalysisDataSourceConfig { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired @Qualifier("analysisDataSource") private DataSource analysisDataSource; @Bean(name="transactionManagerAnalysis") public DataSourceTransactionManager analysisTransactionManager() { return new DataSourceTransactionManager(analysisDataSource); } @Bean(name = "sqlSessionFactoryAnalysis") public SqlSessionFactory sqlSessionFactoryBean() throws Exception{ logger.info("===== sqlSessionFactoryAnalysis build"); SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(analysisDataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*.xml")); return bean.getObject(); } @Bean(name = "sqlSessionTemplateAnalysis") public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
Main data source spring data jpa
If the primary is JPA, in spring boot, there is no need to configure it. You can configure it without configuration, but you can also configure it
package com.newpearl.da.service.config; import org.hibernate.cfg.ImprovedNamingStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManager; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; /** * @author tanjiayao * @Description * @date 2018-10-22 */ @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef="entityManagerFactoryPrimary", transactionManagerRef="transactionManagerPrimary", basePackages= { "com.newpearl.da.biz.dao"}) //Set Repository location public class PrimaryDataSourceConfig { @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Primary @Bean(name = "entityManagerPrimary") public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactoryPrimary(builder).getObject().createEntityManager(); } @Primary @Bean(name = "entityManagerFactoryPrimary") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) { return builder.dataSource(primaryDataSource) .packages("com.newpearl.o2o.api.model") .persistenceUnit("primary") .properties(buildProperties()) .build(); } @Primary @Bean(name="transactionManagerPrimary") public PlatformTransactionManager primaryTransactionManager(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); } // Public jpa settings // @Value("${spring.jpa.hibernate.ddl-auto}") // String dll; // @Value("${spring.jpa.properties.hibernate.dialect}") // String dialect; // @Value("${spring.jpa.show-sql}") // String showSql; private Map<String, Object> buildProperties() { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("hibernate.ejb.naming_strategy", ImprovedNamingStrategy.class.getName()); // properties.put("hibernate.hbm2ddl.auto", dll); // properties.put("hibernate.dialect", dialect); properties.put("hibernate.show_sql", false); return properties; } }