MyBatis对动态SQL中使用trim标签的场景及效果介绍比较少。
看起来有点难理解,简单点来说--trim标签有点类似于replace效果。
trim标签有如下属性:
prefix:前缀覆盖并增加其内容
suffix:后缀覆盖并增加其内容
prefixOverrides:前缀判断的条件
suffixOverrides:后缀判断的条件
通过百度以及自己测试:实践是检验真理的唯一标准!
替代where标签:
首先对UserMapper.xml中的SQL进行修改:
替代set标签:(截图有限,直接上代码)
1 <update id="updateById"> 2 update sys_user 3 <trim prefix="SET" suffixOverrides="," suffix="where id =#{id}"> 4 <if test="userName != null and userName !=''"> 5 user_name =#{userName}, 6 </if> 7 <if test="userPassword != null and userPassword != ''"> 8 user_password =#{userPassword}, 9 </if> 10 <if test="userEmail != null and userEmail != ''"> 11 user_email =#{userEmail}, 12 </if> 13 <if test="userInfo != null and userInfo != ''"> 14 user_info =#{userInfo}, 15 </if> 16 <if test="headImg != null"> 17 head_img =#{headImg}, 18 </if> 19 <if test="createTime != null"> 20 create_time =#{createTime}, 21 </if> 22 id =#{id} 23 </trim> 24 </update>
这样跟原来的where,set标签一对比,其实也就是一个替代作用!
我不是很确认这种用法的具体场景,但是,就目前mybatis的动态sql语句来看的话,很多标签都足够用了。