org.apache.ibatis.ognl.OgnlException: source is null for getProperty(null, “xxxx“)] with root cause

在使用MyBatis时,遇到这样的问题:
org.apache.ibatis.ognl.OgnlException: source is null for getProperty(null, "name")] with root cause

    <select id="getTotal" resultType="java.lang.Long">
        select count(*) from employee e
        <where>
        <!--<if test="emp !=null">-->
            <if test="emp.name != null and emp.name!=''">
                and e.name like concat('%',#{emp.name},'%')
            </if>
            <if test="emp.politicId != null">
                and e.politicId =#{emp.politicId}
            </if>
            <if test="emp.jobLevelId != null">
                and e.jobLevelId =#{emp.jobLevelId}
            </if>
            <if test="emp.posId != null">
                and e.posId =#{emp.posId}
            </if>
            <if test="emp.nationId != null">
                and e.nationId =#{emp.nationId}
            </if>
            <if test="emp.departmentId != null">
                and e.departmentId =#{emp.departmentId}
            </if>
            <if test="emp.engageForm != null">
                and e.engageForm =#{emp.engageForm}
            </if>
            <if test="beginDateScope !=null">
                and emp.beginDate between #{beginDateScope[0]} and #{beginDateScope[1]}
            </if>
        <!--</if>-->
        </where>
    </select>
怎么出现问题的?

我在Mapper接口中定义了getTotal方法,在Service中调用这个方法,方法中需要传入一个Employee对象(在mapper中使用@Param注解取别名emp),我在调用时传入的值为null.

出现的什么问题?

报错:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 'emp.name != null and emp.name!='''. Cause: org.apache.ibatis.ognl.OgnlException: source is null for getProperty(null, "name")] with root cause

org.apache.ibatis.ognl.OgnlException: source is null for getProperty(null, "name")
为什么出现这个问题?

经过谷歌发现,这个异常是MyBatis封装的,类似空指针异常,xml其实是Mapper接口的一个实现类,当一个为null的对象传入后,在xml的方法中使用这个值,就报这个错

解决:

可以在xml中增加对emp对象的判空语句,就是在上文中注释掉的xml语句,更改后,如果emp为null,就不执行where语句

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值