mybatisplus多数据源配置和mybatisplus Invalid bound statement

mybatisplus多数据源配置和mybatisplus Invalid bound statement ,第1张

mybatisplus Invalid bound statement (not found)的问题我看网上都说是xml配置问题,浪费了一天的时间,但也有一种可能:

要用mybatisplus的MybatisSqlSessionFactoryBean, 而不是mybatis的SqlSessionFactory,否则会报mybatisplus Invalid bound statement (not found),丫的,大坑。

mybatisplus的主数据源配置如下,其它的数据源将@Primary删除


import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.hmg_quartz.mapper.cos", sqlSessionTemplateRef  = "db1SqlSessionTemplate")
//此处的basePackages指向的是你存放数据库db1的mapper的包
public class DataSource1Config {

    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1")//指向yml配置文件中的数据库配置
    @Primary    //主库加这个注解,修改优先权,表示发现相同类型bean,优先使用该方法。
    public DataSource dbDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "db1SqlSessionFactory")
    @Primary
    //这里要用mybatisplus的MybatisSqlSessionFactoryBean,
    // 而不是mybatis的SqlSessionFactory,否则会报mybatisplus Invalid bound statement (not found),丫的,大坑。
    public MybatisSqlSessionFactoryBean dbSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        //这个的getResources指向的是你的mapper.xml文件,相当于在yml中配置的mapper-locations,此处配置了yml中就不用配置,或者说不会读取yml中的该配置。
        return bean;
    }

    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager dbTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/876282.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存