基于mybatis的spring boot双数据源配置踩坑笔记

最近工程中需要配置双数据源,按照网络上教程配置以后不能用。

主要的错误有两个,一个是找不到mapper文件。一个是无法连接数据库。

通过网上各种百度最后把问题解决。

解决第一个问题需要一下几点

无法找到mapper最容易想到的问题可以参考一下博文

https://blog.****.net/sundacheng1989/article/details/81630370

简单的说就是名字对不上或则路径写错。

我遇到的问题如下

1、@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})  去掉默认数据源的初始化。

基于mybatis的spring boot双数据源配置踩坑笔记

2、另外mapper接口文件和mapper的xml文件的配置最好也是在每个数据源的地方进行配置。而不是单一数据源时在properties文件中进行配置。

基于mybatis的spring boot双数据源配置踩坑笔记

 

基于mybatis的spring boot双数据源配置踩坑笔记

 

其中一个的数据源配置文件如下

@Configuration
@MapperScan(basePackages = "com.xxx.yyy.dao.icpmg", sqlSessionFactoryRef = "dataSecondSqlSessionFactory")
public class DataSourceSecond {

    /**
     * 返回data2数据库的数据源
     *
     * @return
     */
    @Bean(name = "dataSecondSource")
    @ConfigurationProperties(prefix = "spring.datasource.data2")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 返回data2数据库的会话工厂
     *
     * @param ds
     * @return
     * @throws Exception
     */
    @Bean(name = "dataSecondSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSecondSource") DataSource ds) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/icpmg/*.xml"));
        return bean.getObject();
    }

    /**
     * 返回data2数据库的会话模板
     *
     * @param sessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "dataSecondSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("dataSecondSqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {
        return new SqlSessionTemplate(sessionFactory);
    }

    /**
     * 返回data2数据库的事务
     *
     * @param ds
     * @return
     */
    @Bean(name = "dataSecondTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSecondSource") DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }

}

 

 

 

第二个问题的解决方法,无法连接数据库的问题。

1、配置文件中的数据源配置方法和单一数据源是有差别的。包括url 配置 标签的写法和driver的写法

基于mybatis的spring boot双数据源配置踩坑笔记

 

可以参考的博文

https://blog.****.net/m0_37872413/article/details/91352507

https://blog.****.net/sundacheng1989/article/details/81630370