mybatis启动报错,sqlSession 或者 sqlSessionTemplate报错

首先看一下错误日志
日志1:Error creating bean with name ‘nShopScoreActivityMapper’: Unsatisfied dependency expressed through field ‘sqlSession’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘sqlSessionTemplate’ defined in class path resource[org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method ‘sqlSessionTemplate’ parameter 0;
日志2:Could not resolve type alias ‘BaseResultMap’. Cause: java.lang.ClassNotFoundException: Cannot find class: BaseResultMap

简单的贴一下项目代码

    <resultMap id="BaseResultMap"
        type="com.gomeplus.bs.interfaces.score.entity.NShopScoreRule">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="join_id" property="joinId" jdbcType="INTEGER" />
    </resultMap>
    <!-- 排查完之后,才发现,此处应该是resultMap而不应该是resultType。又因为是generator生成的配置文件,我们
    的result标签的id的属性都是BaseResultMap,排查问题的时候也是有些麻烦的,其实,我们可以把每个页面的
    BaseResultMap重新定义一下,这样也好方便我们查询 -->
    <!-- <select id="selectByPrimaryKey" resultMap="BaseResultMap" -->
    <select id="selectByPrimaryKey" resultType="BaseResultMap"
        parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List" />
        from nshop_score_rule
        where id = #{id,jdbcType=INTEGER}
    </select>

日志分析
这个日志,其实报的是xml的错误,mybatis会把第一个mapper.xml文件给抛出来,也就是nShopScoreActivityMapper.xml。这会让你以为是那个配置文件的问题,但事实上不一定是那个配置文件的问题,可能是其余的mapper的问题,但可以确定的是,应该是就是mybatis的配置文件的问题。
再看日志2,说Could not resolve type alias ‘BaseResultMap’,那么可能是一个别名叫BaseResultMap的附近引发的问题。

代码报错的场景是
项目之前一直都是好使的,就是在项目合并的时候,合并完同事代码,再启动的时候,mybatis就报这个错误。

问题解决步骤
1.在junit测试类中写测试,启动项目,查看项目是否能启动
2.在mybatis-config.xml中,少引入几个配置文件,也就是mappers标签中引入的资源少引入几个,先引入一个,启动下再试试看好不好使
3.最终发现,我的项目是引入到一个 NShopScoreRuleMapper.xml 配置文件,启动报错的
4.排查 NShopScoreRuleMapper.xml 文件,尤其是 BaseResultMap 附近的内容,最终发现问题所在:
问题就是resultMap被同事写成了resultType。

<select id="selectByPrimaryKey" resultType="BaseResultMap"/>

修改代码为

<select id="selectByPrimaryKey" resultMap="BaseResultMap"/>

5.问题解决

问题反思
1.真的,不管怎样,一定要在本地代码没问题,才能提交代码,要不然,真的是很麻烦的
2.如果之前好使,那就看一下日志,把项目版本还原到上一个版本,再试试好使不
3.看一下本次代码合并过来的是什么内容,重点排查下这部分更新下来的代码
4.mybatis的实体类,尽量全用 包装类(Integer、Long)这样的修饰,因为有的时候,我们可能在mapper配置文件中配置的时候,大多数习惯都是按照对象为null的判断,这种时候,你要是一个对象中没有传那个值得话,mybatis可能就会报空指针的异常
5.感觉有必要撸一下mybatis的源码了啊

猜你喜欢

转载自blog.csdn.net/u012489091/article/details/80688978