===========================多数据源配置==============================
配置文件application.properties:
#多数据源配置 spring.datasource.db1.url=jdbc:mysql://localhost:3306/hibernate?useSSL=false spring.datasource.db1.username=root spring.datasource.db1.password=root spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver spring.datasource.db2.url=jdbc:mysql://localhost:3306/spring?useSSL=false spring.datasource.db2.username=root spring.datasource.db2.password=root spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
数据库配置DatasourceConfigure.java:
package com.bxw.configuration; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; @Configuration public class DataSourceConfigure { @Bean(name = "db1") @ConfigurationProperties(prefix = "spring.datasource.db1") // application.properteis中对应属性的前缀 public DataSource dataSource1() { return DataSourceBuilder.create().build(); } @Bean(name = "db2") @ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中对应属性的前缀 public DataSource dataSource2() { return DataSourceBuilder.create().build(); } }
采用spring注解方式注入数据源,数据源名称分别为db1,db2
注入sessionFactory,sessionTemplate
MybatisDBAConfig.java
package com.bxw.configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = {"com.bxw.mapperB"},sqlSessionFactoryRef = "sqlSessionFactory1") public class MybatisDBAConfig { @Autowired @Qualifier("db1") private DataSource db1; @Bean public SqlSessionFactory sqlSessionFactory1() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(db1); // 使用db1数据源, 连接hibernate库 return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate1() throws Exception { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory return template; } }
MybatisDBBConfig.java
package com.bxw.configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = {"com.bxw.mapperA"},sqlSessionFactoryRef = "sqlSessionFactory2") public class MybatisDBBConfig { @Autowired @Qualifier("db2") private DataSource db2; @Bean public SqlSessionFactory sqlSessionFactory2() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(db2); // 使用db1数据源, 连接hibernate库 return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate2() throws Exception { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2()); // 使用上面配置的Factory return template; } }
该配置配置过后,在com.bxw.mapperA和com.bxw.mapperB两个包中的mapper分别使用不同的数据源。
==================================sprIngboot动态数据源=============================================
DBConfig1.java:
package com.bxw.configuration; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "spring.datasource.db1") public class DBConfig1 { private String url; private String password; private String username; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
通过@ConfigurationProperties注入数据源的属性值。
DBConfig2.java:
package com.bxw.configuration; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "spring.datasource.db2") public class DBConfig2 { private String url; private String password; private String username; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
DatasourceContextHolder.java:
package com.bxw.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatasourceContextHolder { public static final Logger log = LoggerFactory.getLogger(DatasourceContextHolder.class); public static final String primary_DB = "db1"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); //设置数据源名 public static void setDB(String dbType){ log.debug("切换到{}数据源",dbType); contextHolder.set(dbType); } //获取数据源名 public static String getDB(){ return contextHolder.get(); } //清除数据源名 public static void clearDB(){ contextHolder.remove(); } }
自定义数据源管理类。
DynamicDatasource.java:
package com.bxw.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDatasource extends AbstractRoutingDataSource { private static Logger log = LoggerFactory.getLogger(DynamicDatasource.class); @Override protected Object determineCurrentLookupKey() { log.debug("数据源为{}",DatasourceContextHolder.getDB()); return DatasourceContextHolder.getDB(); } }
DatasourceConfigure.java
package com.bxw.configuration; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; @Configuration public class DataSourceConfigure { //动态数据源 @Bean(name="dynamicDB1") public DataSource dataSource(){ DynamicDatasource dynamicDatasource = new DynamicDatasource(); //默认数据源 dynamicDatasource.setDefaultTargetDataSource(dataSource1()); Map<Object,Object> dbMap = new HashMap(5); dbMap.put("db1",dataSource1()); dbMap.put("db2",dataSource2()); dynamicDatasource.setTargetDataSources(dbMap); return dynamicDatasource; } }
配置动态数据源。
MybatisDBCConfig.java:
package com.bxw.configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; /** * 动态数据源 */ @Configuration @MapperScan(basePackages = {"com.bxw.mapperDynamic"},sqlSessionFactoryRef = "sqlSessionFactory3") public class MybatisDBCConfig { @Autowired @Qualifier("dynamicDB1") private DataSource dynamicDB1; @Bean public SqlSessionFactory sqlSessionFactory3() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dynamicDB1); // 使用db1数据源, 连接hibernate库 return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate3() throws Exception { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory3()); // 使用上面配置的Factory return template; } }
自定义注解DB.java:
package com.bxw.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface DB { String value() default "db1"; }
StudentService.java
package com.bxw.service; import com.bxw.annotation.DB; import com.bxw.entity.Student; import com.bxw.mapperTA.StudentMapperTA; import com.bxw.mapperTB.StudentMapperTB; import com.bxw.mapperDynamic.StudentMapperC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Service public class StudentService { @Autowired private StudentMapperC studentMapperC; /** * 动态数据源 */ @DB public List<Student> db1(){ return studentMapperC.findAll(); } @DB("db2") public List<Student> db2(){ return studentMapperC.findAll(); } }
@DB根据不同值切换数据源。