zoukankan      html  css  js  c++  java
  • 解决使用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();
                }
            }
        }
    

      

  • 相关阅读:
    Python编程题24--回文数
    Python编程题23--移动零
    Python编程题22--只出现一次的数字
    Python编程题21--每日温度
    Python编程题20--最大子序和
    Python编程题19--比特位计数
    推荐系统中对比实验工具--伯乐bole
    pytorch中反向传播的loss.backward(retain_graph=True)报错
    win10彻底禁止自动更新(家庭版操作)
    linux使用清华源安装工具,切换清华源
  • 原文地址:https://www.cnblogs.com/lythen/p/14865425.html
Copyright © 2011-2022 走看看