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();
}
以此记录。