sprintBoot + mybatis报错:org.apache.ibatis.binding.BindingException: Invalid bound statement
项目报这个异常,认核对了:
1、mapper.xml的命名空间(namespace)是否跟mapper接口的包名一致?
2、接口的方法名,与xml中的一条sql标签的id一致
3、如果接口中的返回值List集合(不知道其他集合也是),那么xml里面的配置,尽量用resultMap(保证resultMap配置正确),不要用resultType
认真核对后均没有问题,application.properties里配置如下:
很显然异常是在说没找到对应的方法,或者说没有对应方法的sql。
之前配置xml方式的mybatis都是在application.properties中添加一行
mybatis.mapper-locations=classpath:mappers/**/*.xml
就行了。但是始终报异常。后来发现是多数据源的问题
因为多数据源是通过@contigration注解的Java类编程配置的,所以这种方式并不能读取到mapper的xml文件在哪。
解决方法是分别在mybatis配置类中生成SqlSessionFactory的方法中配置mapper路径
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mappers/**/*.xml"));
package com.zm.appletinterface.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration(value = "zzymoracle")
@MapperScan(basePackages = "com.zm.appletinterface.dao",sqlSessionTemplateRef = "orcaleSqlSessionTemplate")
public class Org8DataSourceConfig {
@Bean(name = "oracleDataSource")
@ConfigurationProperties(prefix = "spring.datasource.zzymoracle")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "oracleSqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("oracleDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//bean.setMapperLocations(new PathMatchingResourcePatternResolver()
// .getResources("classpath:mapper/**/*.xml"));
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml"));
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name = "oracleTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("oracleDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "orcaleSqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("oracleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}