关于springboot+mybatis 配置多数据源打印sql语句失效的问题

当我们springboot整合mybatis时,可以打印sql语句

当我们springboot整合mybatis时,在单数据源的情况下,可以通过

#打印sql语句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

但是当我们配置多数据源时,使用mybatis.configuration.log-impl无法打印sql语句

控制台打印大信息为

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5c204c23] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1363932663 wrapping com.mysql.cj.jdbc.ConnectionImpl@3f4319cd] will not be managed by Spring
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5c204c23]

原因:因为(mybatis.configuration.log-impl)tk.mybatis 当SqlSessionFactory不存在定义的时候定义SqlSessionFactory;而我们配置多数据源时,重新定义了SqlSessionFactory;因此,如果要打印sql 语句的话,需在我们配置多数据源的SqlSessionFactory时添加MybatisProperties;

解决 在数据库配置时

只需在某一个配置多数据源的配置上加入MybatisProperties就可以

    @Bean(name = "SecondarySessionFactory")
    public SqlSessionFactory SecondarySessionFactory(@Qualifier("SecondaryDataSource") DataSource dataSource , MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfiguration(mybatisProperties.getConfiguration());
        return bean.getObject();
    }

结果(完美解决)

连接主数据库test时 http://localhost:8080/test/getListOfTuser 打印的sql语句

在这里插入图片描述

连接主数据库cbh时 http://localhost:8080/cbh/getListOfTuserByCBH 打印的sql语句

在这里插入图片描述

发布了15 篇原创文章 · 获赞 4 · 访问量 1451

猜你喜欢

转载自blog.csdn.net/qq_40791070/article/details/100665502