整体项目结构
4.0.0
com.sz
MybatisDataSourcesDemo
0.0.1-SNAPSHOT
MybatisDataSourcesDemo
MybatisDataSourcesDemo
1.8
UTF-8
UTF-8
2.3.7.RELEASE
com.baomidou
mybatis-plus-boot-starter
3.5.2
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.projectlombok
lombok
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
2.3.7.RELEASE
com.sz.mybatisdatasourcesdemo.MybatisDataSourcesDemoApplication
repackage
repackage
DataSource -> SqlsessionFactory -> SqlSessionTemplate
-> DataSourceTransactionManager
@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds1",sqlSessionTemplateRef = "db1SqlSessionTemplate")
@Component
public class DS1DataSourceConfig {
@Bean
// 给DataSource 绑定属性值
@ConfigurationProperties(prefix = "ds1")
//创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
//候选的数据源有
//"com.zaxxer.hikari.HikariDataSource",
// "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
public DataSource ds1DataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory ds1SqlsessionFactory (
@Qualifier("ds1DataSource")DataSource dataSource
)throws Exception
{
// 工厂bean SqlSessionFactory
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//设置数据源
bean.setDataSource(dataSource);
//加载映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds1/*.xml"));
return bean.getObject();
}
@Bean
// 数据源事务管理器
public DataSourceTransactionManager db1TransactionManager(@Qualifier("ds1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("ds1SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds2",sqlSessionTemplateRef = "ds2SqlSessionTemplate")
@Component
public class DS2DataSourceConfig {
@Bean
// 给DataSource 绑定属性值
@ConfigurationProperties(prefix = "ds2")
//创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
//候选的数据源有
//"com.zaxxer.hikari.HikariDataSource",
// "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
public DataSource ds2DataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory ds2SqlsessionFactory (
@Qualifier("ds2DataSource")DataSource dataSource
)throws Exception
{
// 工厂bean SqlSessionFactory
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//设置数据源
bean.setDataSource(dataSource);
//加载映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds2/*.xml"));
return bean.getObject();
}
@Bean
// 数据源事务管理器
public DataSourceTransactionManager ds2TransactionManager(@Qualifier("ds2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
ds1 路径下 与 ds2 路径下各一个 mapper文件 分别由 ds1配置类 与 ds2配置类 去扫描生成代理类
用两个数据库模拟不同的数据源
# 应用名称
spring.application.name=MybatisDataSourcesDemo
mybatis-plus.mapper-locations=classpath:mybatis/mapper/ds1/*.xml,classpath:mybatis/mapper/ds2/*.xml
#ds1
ds1.type=com.alibaba.druid.pool.DruidDataSource
ds1.jdbc-url=jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
ds1.username=root
ds1.password=root
ds1.driver-class-name=com.mysql.cj.jdbc.Driver
#ds2
ds2.type=com.alibaba.druid.pool.DruidDataSource
ds2.jdbc-url=jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
ds2.username=root
ds2.password=root
ds2.driver-class-name=com.mysql.cj.jdbc.Driver
@Autowired
private AnimalService animalService;
@Autowired
private UserService userService;
@Test
void contextLoads() {
animalService.remove(null);
userService.remove(null);
Animal animal = new Animal();
animal.setName("老虎");
animalService.save(animal);
User user = new User();
user.setName("张三");
userService.save(user);
List animals = animalService.list();
System.out.println("animals = " + animals);
List userList = userService.list();
System.out.println("userList = " + userList);
}
分别在 ds1和 ds2库中添加 user 表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oAOOL2gX-1665642551395)(C:/Users/Administrator.DESKTOP-3B5FM5P/AppData/Roaming/Typora/typora-user-images/image-20221013141054547.png)]
版本与 mybatis-plus保存一致
com.baomidou
dynamic-datasource-spring-boot-starter
${version}
spring:
datasource:
dynamic:
# primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
slave_1:
url: jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
slave_2:
url: jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
@Service
public class UserServiceImpl
extends ServiceImpl
implements UserService {
@Override
@DS("slave_1")
public List findAllDS1()
{
return this.baseMapper.selectList(null);
}
@Override
@DS("slave_2")
public List findAllDS2()
{
return this.baseMapper.selectList(null);
}
}
@Test
void testDS()
{
List allDS1 = userService.findAllDS1();
System.out.println("allDS1 = " + allDS1);
List allDS2 = userService.findAllDS2();
System.out.println("allDS2 = " + allDS2);
}