解决使用mybatis-plus报错Invalid bound statement (not found)错误

  这个问题昨晚花了很长时间去查资料,其实网上的方法已有很多,但都解决不了。于是从spring初始化mybatis开始看起,发现程序不是没有扫描到mybatis-plus配置,而是压根没有去扫描。为什么呢?

  因为:SessionFactoryBean是自定义的,不是spring自动注入的!

       然后又会有个问题,不是有@MapperScan么?怎么就没扫描xml文件呢?通过断点发现,mybatis-locations这个匹配是由sessionFactoryBean去配置的,@MapperScan扫描的时候,会扫描mapper类包,然后从sessionFactoryBean中取xml的匹配,然而,自定义的SqlSession并没有去设置mybatisLocation这个参数,这时候就会当没xml文件处理。在执行方法的时候,mybatis需要去找statement,当然就找不到了。

  所以解决问题的办法也很简单,有三种解决方式

  1. 用自动注入的sessionFactoryBean

  2. 手动设置sessionFactoryBean.setMybatisLocation : new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/*.xml")

  3.把xml文件放到mapper同级目录下,这个参考代码,当没有设置xml路径时,会在当前类的同级路径下去找xml文件,这样找到也可以。

  

private void loadXmlResource() {
        // Spring may not know the real resource name so we check a flag
        // to prevent loading again a resource twice
        // this flag is set at XMLMapperBuilder#bindMapperForNamespace
        if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
            String xmlResource = type.getName().replace('.', '/') + ".xml";
            // #1347
            InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
            if (inputStream == null) {
                // Search XML mapper that is not in the module but in the classpath.
                try {
                    inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
                } catch (IOException e2) {
                    // ignore, resource is not required
                }
            }
            if (inputStream != null) {
                XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
                xmlParser.parse();
            }
        }
    }

  

原文地址:https://www.cnblogs.com/lythen/p/14865425.html