spring boot2.x版本学习笔记之使用mybatis进行多数据源配置访问数据库

  1. 首先创建2个用于测试的数据库,每个数据库中都创建一张user表,建表语句如下:
CREATE TABLE `user`  (
  `id` bigint(20) NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

  1. 创建一个spring boot项目,项目结构如下:
    在这里插入图片描述
  2. 导入相关的maven依赖:
		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
  1. 编写多数据源配置文件:
spring:
  datasource:
    # 第一个数据源
    first:
      # 多数据源配置中url替换成jdbc-url
      jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
    # 第二个数据源
    second:
      jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp-second?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver


mybatis:
  mapper-locations: classpath:/mapper/**/*.xml # mapper文件位置

logging:
  level:
    root: info
    com.learn.mapper: debug

注意:多数据源配置中,url属性名称需要替换成jdbc-url

  1. 初始化数据源:
  • first数据源
@Configuration
@MapperScan(basePackages = "com.learn.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfig {

    @Bean(name = "firstDataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "firstSqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        // mapper文件位置
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/first/**/*.xml"));
        return bean.getObject();
    }

    @Bean("firstSqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate firstSqlSessionTemplate(
            @Qualifier("firstSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

}
  • second数据源
@Configuration
@MapperScan(basePackages = "com.learn.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {

    @Bean(name = "secondDataSource")
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondSqlSessionFactory")
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/second/**/*.xml"));

        return bean.getObject();
    }

    @Bean("secondSqlSessionTemplate")
    public SqlSessionTemplate secondSqlSessionTemplate(
            @Qualifier("secondSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}
  1. 编写数据库User实体类
  • first数据源
@Data
public class FirstUser {

    private Long id;

    private String name;

    private Integer age;
}
  • second数据源
@Data
public class SecondUser {

    private Long id;

    private String name;

    private Integer age;
}
  1. 创建UserMapper文件:
  • first数据源
public interface FirstUserMapper {

    /**
     * 通过id获取用户信息
     *
     * @param id
     * @return
     */
    @Select("select * from user where id = #{id}")
    public FirstUser getFirstUserById(Long id);

    /**
     * 保存用户信息
     *
     * @param firstUser
     * @return
     */
    public int insertFirstUser(FirstUser firstUser);
}
  • second数据源
public interface SecondUserMapper {

    /**
     * 通过id获取用户信息
     *
     * @param id
     * @return
     */
    @Select("select * from user where id = #{id}")
    public SecondUser getSecondUserById(Long id);

    /**
     * 保存用户信息
     *
     * @param secondUser
     * @return
     */
    public int insertSecondUser(SecondUser secondUser);
}

这里Mapper文件使用了注解和xml文件相结合的方式。

  1. 创建UserMapper相关xml配置文件
  • first数据源,FirstUserMapper.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.learn.mapper.first.FirstUserMapper">

    <insert id="insertFirstUser">
        INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
    </insert>
</mapper>
  • second数据源,SecondUserMapper.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.learn.mapper.second.SecondUserMapper">

    <insert id="insertSecondUser">
        INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
    </insert>
</mapper>
  1. 编写测试用例:
@SpringBootTest
class SpLearnMybatisMultiDataSourceApplicationTests {

    @Autowired
    private FirstUserMapper firstUserMapper;

    @Autowired
    private SecondUserMapper secondUserMapper;

    @Test
    void testUserMapper() {
        FirstUser firstUser = new FirstUser();
        firstUser.setId(7777L);
        firstUser.setName("我是First数据源保存的");
        firstUser.setAge(100);
        //保存
        firstUserMapper.insertFirstUser(firstUser);
        //查询
        System.out.println(firstUserMapper.getFirstUserById(7777L));
        SecondUser secondUser = new SecondUser();
        secondUser.setId(8888L);
        secondUser.setName("我是Second数据源保存的");
        secondUser.setAge(0);
        //保存
        secondUserMapper.insertSecondUser(secondUser);
        //查询
        System.out.println(secondUserMapper.getSecondUserById(8888L));
    }

}
  1. 测试结果:

在这里插入图片描述
可以看到使用不同的数据源配置的mapper对象保存,数据成功保存到了不同的数据库中。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder-文小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值