SpringBoot集成MyBatis出现异常:org.apache.ibatis.binding.BindingExceptionInvalid bound statement (not found

异常信息

在SpringBoot集成MyBatis时,mapper一直扫描不到,出现异常:

{“timestamp”:1525862042241,”status”:500,”error”:”Internal Server Error”,”exception”:”org.apache.ibatis.binding.BindingException”,”message”:”Invalid bound statement (not found): com.example.demo3.dao.AuthorMapper.insertSelective”,”path”:”/author/add”}

异常原因

没有在application.properties中配置mybatis.mapper-locations=classpath*:com/example/demo3/mapper/*Mapper.xml 或者 在配置SqlSessionFactory时未设置MapperLocations导致mapper文件没有被加载,有时都配置后出现还会出现此问题,问题原因不明。

解决方法

  1. 在application.properties文件中添加配置 mybatis.mapper-locations
  2. 配置mybatis时添加配置
@Configuration
public class MyBatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws IOException {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/example/demo3/mapper/*Mapper.xml");
        sessionFactory.setMapperLocations(resources);
        return sessionFactory;
    }
}

在这里尤其要注意mapper文件所在位置路径的书写,如果mapper文件放在resources下可以直接使用classpath:mapper/*.xml,如果放在src下的src/main/jar下的包中,必须使用classpath*:com/example/demo/mapper/*.xml

关于classpath和classpath:*的区别:
https://blog.csdn.net/kkdelta/article/details/5507799
http://www.jb51.net/article/137029.htm

如果以上两种方法尝试后,还会出现此异常,只能强制将mapper文件打包,在pom.xml文件中进行配置,通过配置后问题得到了解决,但为什么要这样,不清楚。。。

<resources>
    <resource>
        <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        <filtering>false</filtering>
    </resource>
</resources>

此解决方法参考博文:https://blog.csdn.net/qinkang1993/article/details/57626434

猜你喜欢

转载自blog.csdn.net/sinat_36553913/article/details/80258771