關於SpringBoot結合mybatis後遇到的坑
- 2021 年 5 月 3 日
- 筆記
- mybatis, springboot, 文件配置
先放出我遇到的出錯資訊,真的出錯了可以先看看出錯資訊,就能更加高效準確的搜索到資訊
我的報錯日誌:
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
注釋掉這一行即可
(記得報錯資訊著重看最後的報錯資訊,因為異常捕獲是從上而下的,最後的才是最底層的報錯,也更準確)