关于mybatis中基本类型条件判断问题

本文介绍在MyBatis中使用动态SQL时遇到的关于参数解析的问题及三种解决方案,包括修改SQL语句、注解参数和使用HashMap或对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:发现问题


sql动态语句中如果 parameterType="int"


<select id="sel_campusinfo" parameterType="int" resultType="Campusinfo">  
        select cmpid,cmpname from campusinfo where state!='d' and cmpid=#{cmpid}  
 </select>  
是正确的,但是如果加上if test
[html] view plain copy
<select id="sel_campusinfo" parameterType="int" resultType="Campusinfo">  
        select cmpid,cmpname from campusinfo where state!='d' and cmpid!=0  
        <if test="cmpid!=0">and cmpid=#{cmpid}</if>  
</select> 


则报错:
There is no getter for property named 'cmpid' in 'class java.lang.Integer'   


出错原因:Mybatis默认采用ONGL解析参数,所以会自动采用对象树的形式取Integer.cmpid。Integer对象没有cmpid属性。
如果不解析参数,mybatis自动识别传入的参数,不会报错。




二:解决办法


1.修改select语句
<select id="sel_campusinfo" parameterType="int" resultType="Campusinfo">  
select cmpid,cmpname from campusinfo where state!='d' and cmpid!=0  
<if test="_parameter!=0">and cmpid=#{_parameter}</if>  
</select>  


参数名全部改为_parameter。
2.不修改sql,只修改接口


接口类:


Campusinfo sel_campusinfo( int cmpid);  
改为:


Campusinfo sel_campusinfo(@Param(value="cmpid") int cmpid);  


3.可以将参数包装在hashmap或者对象中作为参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值