欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

mybatis的动态sql之if test的使用说明

时间:2021-08-04 08:33:15|栏目:JAVA代码|点击:

参数为String,if test读取该参数代码

<select id="getMaxDepartId" parameterType="java.lang.String" resultType="java.lang.String">
    SELECT MAX(DEPART_ID) FROM T_P_DEPART 
    <where>
      <if test="_parameter!=null and _parameter!=''"> 
        AND DEPART_PID = #{departId,jdbcType=VARCHAR} 
      </if>
      <if test="_parameter==null or _parameter==''"> 
        AND DEPART_PID IS NULL
      </if>
    </where>
  </select>

参数为pojo , if test读取该参数代码

<select id="findShopByName" parameterType="ShopVo" resultType="ShopCustomer">
  select * from shop 
  <where>
      <if test="shopCustomer.shopname!=null and shopCustomer.shopname!=''">
        shop.shopname like '%${shopCustomer.shopname}%'
      </if>
      <if test="shopCustomer.shopname==null or shopCustomer.shopname==''"> 
        AND shop.shopname is null
      </if>
  </where>
</select>

补充:关于mybatis中 if test的条件怎么写

1.mybatis 中 的 if test写法

1.1官方文档上对于if是这么写的

<if test="title != null">
  AND title like #{title}
</if>

参考官方文档:

实际项目中会有这种情况: 页面上title字段输入某个值进行查询,手动将输入框中的值删除,然后再次查询,发现结果不正确,究其原因是应为title传入了空串" " 这样在mybatis配置文件中就会用空串进行查询,导致出现错误结果

1.2建议写法

<if test="title != null and title != ''" >
  AND title like #{title}
</if>

2.使用mybatis 做修改时将字段置空

if中如果传入的参数如果为空,那么将不会执行if中的语句

解决办法:

<update id="updateObject" parameterType="*.*.Object" >
update table
 <set>
  <if test="Object.fullName == null or Object.fullName ==''">
  full_name = null,
  </if>
  <if test="Object.fullName != null and Object.fullName !=''">
  full_name = #{companyOrg.fullName},
  </if>
  <if test="Object.level == null or Object.level ==''">
  level = null,
  </if>
  <if test="Object.level == 0 ">
  level = null,
  </if>
  <if test="Object.level != null and Object.level !='' and Object.level != 0 ">
  level = #{companyOrg.level},
  </if>
 
 </set>
 where 1=1 and id =#{companyOrg.id}
</update>

上一篇:spring boot添加新模块的方法教程

栏    目:JAVA代码

下一篇:Maven引入外部jar的几种方法(小结)

本文标题:mybatis的动态sql之if test的使用说明

本文地址:http://www.codeinn.net/misctech/164049.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有