【mybatis】MyBatis报OgnlException: source is null for getProperty(null, “id”)异常

朱雀 2022-04-25 10:16 303阅读 0赞

先看下面的mapper中的写法

  1. <sql id="where">
  2. <if test="requestStudent.id!=null and requestStudent.id!=''">
  3. and tb.id = #{requestStudent.id}
  4. </if>
  5. <if test="requestStudent.name!=null and requestStudent.name!=''">
  6. and tb.name = #{requestStudent.name}
  7. </if>
  8. <if test="requestStudent.age!=null and requestStudent.age!=''">
  9. and tb.age = #{requestStudent.age}
  10. </if>
  11. <if test="requestStudent.height!=null and requestStudent.height!=''">
  12. and tb.height = #{requestStudent.height}
  13. </if>
  14. </sql>

MyBatis报OgnlException: source is null for getProperty(null, “id”)异常的原因如下:

以前的MyBatis可以像上面那样直接”requestStudent.id“判断是否为null,现在不行了,要先判断requestStudent是否为null才行(因为requestStudent也是个对象也可能为NULL),否则即使requestStudent不为null也会报source is null for getProperty(null, “id”)异常,即可能会有NPE空指针异常。

解决办法:在外层加一个if判断就行了,看下面的改写

  1. <sql id="where">
  2. <if test="requestStudent!=null">
  3. <if test="requestStudent.id!=null and requestStudent.id!=''">
  4. and tb.id = #{requestStudent.id}
  5. </if>
  6. <if test="requestStudent.name!=null and requestStudent.name!=''">
  7. and tb.name = #{requestStudent.name}
  8. </if>
  9. <if test="requestStudent.age!=null and requestStudent.age!=''">
  10. and tb.age = #{requestStudent.age}
  11. </if>
  12. <if test="requestStudent.height!=null and requestStudent.height!=''">
  13. and tb.height = #{requestStudent.height}
  14. </if>
  15. </if>
  16. </sql>

发表评论

表情:
评论列表 (有 0 条评论,303人围观)

还没有评论,来说两句吧...

相关阅读