@mapperscan注解_Springboot2.x整合mybatis多数据源(注解完整版,亲测成功)

并发量的不断增加,单个数据库承受不了这么大的压力,因此一个项目使用多个数据库也越来越重要,当然使用数据库的模式可能不一样,比如说主从模式、分布式模式。不管是哪种模式都是使用的多数据源。Springboot整合mybatis实现多数据源有两种方式:分包和AOP。这里使用的分包,因为层次更加清晰。

以下代码在评论区会给出github地址。OK,开始整合。

一、环境配置

e9b83cafa966fcbe6ffc3d2874fc4b2b.png

环境很简单,下面开始整合。

二、代码整合

新建一个Springboot项目名字叫做SpringbootMybatisMutil,开始下面的操作。

第一步:添加依赖

<dependencies>
        

第二步:修改属性文件

#数据库1的配置
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/uav
?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test1.username = root
spring.datasource.test1.password = root
#数据库2的配置
spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url = jdbc:mysql://localhost:3306/uav2
?useUnicode=true&characterEncoding=utf-8&useSSL=false
#上面的这一行在uav后面添加,代码太长我换成了两行,
spring.datasource.test2.username = root
spring.datasource.test2.password = root
#mybatis依赖
mybatis.type-aliases-package = com.fdd.bean

第三步:新建一个bean包,创建Person类

@Mapper

第四步:新建config包,创建DataSourceConfig1l类

@Configuration 

再建一个DataSourceConfig2类,里面的代码和DataSourceConfig1的一样,把里面的1换成2即可。

第五步:新建mapper1包,创建PersonMapper类

@Mapper

在这里使用注解的形式进行整合。

第六步:新建mapper2包,创建UserMapper类

@Mapper

内容和PersonMapper是一样的,但是我在测试的时候出现了一些bean重复定义的错误,所以没有使用Person2Mapper这种方法进行命名。

第七步:新建controller包,创建MyController类

@RestController

这里只测试了插入的方法,当然如果你需要service层,自行添加就好了。不过对于基本的增删改查功能,mapper足够。

OK,这个就是多数据源的整合,在我自己的电脑亲测成功。

38e711cdf0e038294492af42507ab023.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值