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.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>
        
        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语句

你可能感兴趣的:(MySQL)