软件编程
位置:首页>> 软件编程>> java编程>> 在mybatis中使用mapper进行if条件判断

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

作者:伏特加的滋味  发布时间:2023-08-01 08:09:34 

标签:mybatis,mapper,if

目的:

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

查询sql语句如下:


<select id="queryData" 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 id="ORDER_I" 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>

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

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

来源:https://blog.csdn.net/yuanyuan214365/article/details/72615090

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com