MyBatis中单一简单参数判断null的方法

63 篇文章 11 订阅

比如有这样一个方法:

List<Order> selectListById(Integer id);

只有一个数字类型的参数,而且id参数有可能是null。

如果在xml文件里这样写:

<select id="selectListById" resultMap="baseResultMap" parameterType="java.lang.Integer">
    select *
    from `order` a
    where a.status=0
    <if test="id != null">
        and id = #{id}
    </if>
</select>

会引发异常:

org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer'

异常原因应该是test中的参数只能是parameterType类中的属性,而不是parameterType本身。

 

解决方案有以下几种:

1,方法中加入加@param注解,然后就可以在test中使用名字是id的参数了:

List<Order> selectListById(@param("id") Integer id);

2,如果是Integer类型参数,可以在test里用value参数:

<select id="selectListById" resultMap="baseResultMap" parameterType="java.lang.Integer">
    select *
    from `order` a
    where a.status=0
    <if test="value != null">
        and id = #{id}
    </if>
</select>

因为value就是Integer类里的参数,记录Integer的数字,算是个投机取巧的写法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值