Springboot +Mybatis实现多数据源配置,你会吗?( 二 )

剩下的就是编写我们相应的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/mapping
4.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配置多数据源就大功告成啦 。
好啦,看完之后如果你觉得有所收获,那就点个赞再走呗~




推荐阅读