springboot集成mybatis和druid时mybatis报错:Invalid bound statement (not found)

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

描述:springboot的starter和autoconfig,在使用mybatis时不需要再需要繁琐的配置,只需要在配置文件中配置mybatis属性spring就可以自动配置好相关的类。今天换了数据源,使用了Druid,因为springboot默认不支持Druid数据源的自动配置,所以手动写了一个配置类:

@Configuration
public class DruidConfig {
    /*
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: com.mysql.jdbc.Driver           # mysql驱动包
    url: jdbc:mysql://localhost:3306/test              # 数据库名称
    username: root
    password: oracle
    # 下面为连接池的补充设置,应用到上面所有数据源中
    # 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000      # 配置获取连接等待超时的时间
    timeBetweenEvictionRunsMillis: 60000    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}

启动应用后就开始报错,debug发现sqlsessionfactorybean调用时报错(debug具体的信息我当时也没在意,因为表象上感觉是application.yml中配置的mybatis参数没有读到),我又自己写了一个MyBatis的配置类:

@Configuration
@EnableTransactionManagement
@AutoConfigureAfter({DruidDataSource.class})
@MapperScan("org.kumas.eshop.inventory.mapper")
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            //bean.setTypeAliasesPackage("org.kumas.eshop.inventory.model");
            bean.setMapperLocations(resolver.getResources("classpath:/mybatis/mapper/*.xml"));

            return bean.getObject();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

   
}

奇怪的是,加了这个类后程序正常了。我猜测会不会因为构建sqlsessionfactorybean的时候找不到datasource,然后试着在DruidConfig类中给datasource指定了名称,结果果然正常了:

@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
    return new DruidDataSource();
}

以此记录。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值