zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    德信创业系2014版
    [学习笔记]矩形面积并
    第六章 深入分析ClassLoader工作机制
    第五章 深入class文件结构
    设计模式
    第四章 Javac编译原理
    第三章 深入分析Java Web中的中文编码问题
    第2章 深入分析java I/O的工作机制(下)
    linnx常用命令学习
    jenkins学习(1)
  • 原文地址:https://www.cnblogs.com/funkboy/p/14577427.html
Copyright © 2011-2022 走看看