您的位置:首页技术文章
文章详情页

在mybatis中使用mapper进行if条件判断

【字号: 日期:2023-10-20 13:54:46浏览:68作者:猪猪
目的:

在使用mybatis框架中mapper文件有自动生成,但有时需要自己添加sql语句进行开发,当遇到需要使用 if进行条件判断的时候该怎么写?

查询sql语句如下:

<select parameterType='com.pojo.QueryDetailReq' resultType='com.pojo.MxDataInfo'> select * from db_trd.tb_trd_secu_order where order_status=6 <if test='channelNo!= null' > and channel_no = #{channelNo,jdbcType=INTEGER} </if> <if test='reportNo!=null' > and report_no = #{reportNo,jdbcType=INTEGER} </if> <if test='companyNo!= null' > and company_no = #{companyNo,jdbcType=VARCHAR} </if> <if test='orderNo!=null' > and order_no = #{orderNo,jdbcType=INTEGER} </if> <if test='stockCode!=null' > and stock_code = #{stockCode,jdbcType=VARCHAR} </if> </select>语句解析:

1、if语句的格式 ;

2、test中的字段 为parameterType中 com.pojo.QueryDetailReq 的对象 (入参)

3、resultType 为返回查询数据对象 (结果集)

补充:mabatis mapper文件中 使用if条件插入字段和数据

有时候我们插入数据库数据的时候,插入字段都是不确定的,那么我们也可以用if条件来过滤一些字段

废话不多说,直接上代码

<insert parameterType='hashmap'> insert into t_order <trim prefix='(' suffix=')' suffixOverrides=','> <if test='orderNo != null'> orderNo, </if> <if test='serviceName != null'> serviceName, </if> <if test='idcard != null'> idcard, </if> <if test='name != null'> name, </if> <if test='requestData != null'> requestData, </if> <if test='responseData != null'> responseData, </if> <if test='status != null'> status, </if> <if test='updatedTime != null'> updatedTime, </if> <if test='completionTime != null'> completionTime, </if> <if test='bae007 != null'> bae007, </if> <if test='operId != null'> operId, </if> <if test='operName != null'> operName, </if> <if test='remark != null'> remark, </if> </trim> <trim prefix='values (' suffix=')' suffixOverrides=','> <if test='orderNo != null'> #{orderNo}, </if> <if test='serviceName != null'> #{serviceName}, </if> <if test='idcard != null'> #{idcard}, </if> <if test='name != null'> #{name}, </if> <if test='requestData != null'> #{requestData}, </if> <if test='responseData != null'> #{responseData}, </if> <if test='status != null'> #{status}, </if> <if test='updatedTime != null'> #{updatedTime}, </if> <if test='completionTime != null'> #{completionTime}, </if> <if test='bae007 != null'> #{bae007}, </if> <if test='operId != null'> #{operId}, </if> <if test='operName != null'> #{operName}, </if> <if test='remark != null'> #{remark}, </if> </trim> </insert>

经过测试,是可以实现的。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。如有错误或未考虑完全的地方,望不吝赐教。

标签: Mybatis 数据库
相关文章: