關於SpringBoot結合mybatis後遇到的坑

slyblog發表於2021-05-03

先放出我遇到的出錯資訊,真的出錯了可以先看看出錯資訊,就能更加高效準確的搜尋到資訊

我的報錯日誌:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'adminServiceimpl'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminServiceImpl': Unsatisfied dependency expressed through field 'myMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myMapper' defined in file [D:\Program Data\Java_workbench\idea\demo\target\classes\com\example\demo\Mapper\MyMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Program Data\Java_workbench\idea\demo\target\classes\mapper\AdminMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [D:\Program Data\Java_workbench\idea\demo\target\classes\mapper\AdminMapper.xml]'. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.example.demo.Mapper.AdminMapper.BaseResultMap

關鍵在於紅色這一行,這個說我的對映關係已經存在,這一個就說明我極有可能是重複宣告瞭對映關係,也就是mapper,檢查發現我在application.properties檔案和自己配置的mybatis配置檔案中都有說明mapper的位置,這樣會導致對mapper的重複掃描,因此註釋掉其中一個即可,我直接註釋掉application.properties裡的

mybatis.mapper-locations=classpath:mapper/*.xml

註釋掉這一行即可

(記得報錯資訊著重看最後的報錯資訊,因為異常捕獲是從上而下的,最後的才是最底層的報錯,也更準確)

相關文章