• springboot 显式配置数据源 解决mybatis注解无法被识别问题


    1正常来讲,只要在yml 加上数据库配置,然后pom添加相关依赖,带有mapper注解的mybatis接口是可以被springboot识别的,但是如果配置之后出现mapper注解无法被创建bean,或者SqlSessionFactory没有创建的错误,就要显式配置bean ,本做法参照springboot创建多数据源方法 

    创建一个配置类

    @Configuration
    @MapperScan(basePackages = {"com.xxxx.xxxx.xxxxx.mapper"}, sqlSessionFactoryRef = "sqlsession1")
    public class DataSConfig {
        @Bean(name = "test1DataSource")//注入到这个容器
        @ConfigurationProperties(prefix = "spring.datasource")//表示取application.properties配置文件中的前缀
        @Primary    //primary是设置优先,因为有多个数据源,在没有明确指定用哪个的情况下,会用带有primary的,这个注解必须有一个数据源要添加
    
        public DataSource testDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "sqlsession1")
        @Primary
        //@Qualifier("xxx")的含义是告诉他使用哪个DataSource
        public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            return bean.getObject();
        }
    
        @Bean(name = "test1TransactionManager")//配置事务
        @Primary
        public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "test1SqlSessionTemplate")
        @Primary
        public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sqlsession1") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    
    }

    代码来自https://blog.csdn.net/qq_41076797/article/details/82889770

    然后配置yml

    spring:
      datasource:
        username: root
        password: xxxx
        jdbc-url: jdbc:mysql://xxxxx
        driver-class-name: com.mysql.cj.jdbc.Driver
    #不同的springboot版本有差异,如果出错就网上搜一下

    不同的数据源使用不同的mapperscan

    附赠多数据源使用

    封装jar的简易方法http://www.360doc.com/content/20/0129/15/13328254_888499128.shtml

    jdbctemplate多数据源  https://blog.didispace.com/springbootmultidatasource/

    配置连接池 https://blog.51cto.com/zero01/2161509

  • 相关阅读:
    数组模拟链表
    高精度模板
    利用二分法求三次方根
    AcWing 789.数的范围
    二进制中1的个数
    AcWing 787.归并排序
    微信小程序form表单的bindsubmit提交没有效果
    本地项目如果上传到GitHub上
    微信小程序生成随机数
    CSS3 Filter的十种特效
  • 原文地址:https://www.cnblogs.com/funkboy/p/14577427.html
Copyright © 2020-2023  润新知