剩下的就是编写我们相应的xml文件和接口类了,代码如下:
@Component@Mapperpublic interface PrimaryUserMapper { List<User> findAll();}@Component@Mapperpublic interface SecondaryUserMapper { List<User> findAll();}相关的xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jdkcb.mybatisstuday.mapper.one.PrimaryUserMapper"> <select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User"> select * from sys_user; </select></mapper><?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jdkcb.mybatisstuday.mapper.two.SecondaryUserMapper"> <select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User"> select * from sys_user2; </select></mapper>
注:其中xml文件在本实例中目录为:resources/mapping4.2 测试
编写一个Controller用于测试,因为是测试实例且代码相对来说较为简单,所以这里就不写Service层了 。
代码如下:
@RestControllerpublic class UserController { @Autowired private PrimaryUserMapper primaryUserMapper; @Autowired private SecondaryUserMapper secondaryUserMapper; @RequestMapping("primary") public Object primary(){ List<User> list = primaryUserMapper.findAll(); return list; } @RequestMapping("secondary") public Object secondary (){ List<User> list = secondaryUserMapper.findAll(); return list; } }在浏览器分别输入
:http://127.0.0.1:8080/primary 和
http://127.0.0.1:8080/secondary
结果如下:
[{"user_id":1,"user_name":"张三","user_age":25}] //primary [{"user_id":1,"user_name":"李四","user_age":30}] //secondary到此,Springboot结合mybatis配置多数据源就大功告成啦 。
好啦,看完之后如果你觉得有所收获,那就点个赞再走呗~
推荐阅读
- 一篇一看就懂的Https的实现过程梳理
- 有几个国家实现了载人登月 哪些国家探测器登月成功了
- 三星2020年营收-三星到2020年实现销售额4000亿美元-
- SpringBoot+Mysql做登陆接口,抛弃mapper.xml
- 如何运用Spring框架的@Async实现异步任务
- 人生至少有一个梦想?为实现梦想而努力
- 超实用的tomcat启动脚本实现
- 热加载和热部署,没听过?看看 Tomcat 是怎么实现的
- 使用Redis轻松实现秒杀系统
- JavaScript前端各种文件下载功能的实现