Mybatis中运用小技巧 trim标签的使用
2024-09-04 21:20:25
作者:death05的博客
推荐:路在脚下
trim元素的主要功能是可以在自己包含的内容钱加上某些前缀,也可以在其后加上某写后缀,与之对应的属性是prefix和suffix;
可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides。以下举例:
1、代码为:
select * from user
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> AND name=#
{name}</if>
<if test="gender != null and gender.length()>0"> AND gender=#
{gender}</if>
</trim>
假如说name和gender的值都不为null的话,打印的SQL为:
select * from user where name = 'xx' and gender = 'xx'
where后不存在and,这是因为prefixoverride="AND |OR"
代表去掉第一个and或者是or。
2、代码为:
update user
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name} ,
</if>
<if test="gender != null and gender.length()>0"> AND gender=#
{gender} , </if>
</trim>
假如说name和gender的值都不为null的话,打印的SQL为:
update user set name='xx' , gender='xx' where id='x'
可以参考第一个例子理解。
3、代码为:
<insert id="save" parameterType="NoticeEntity">
INSERT INTO S_NOTICE
<trim prefix="(" suffix=")" suffixOverrides=",">
ID,
<if test="title != null">TITLE,</if>
<if test="content != null">CONTENT,</if>
<if test="noticeStatus != null">NOTICE_STATUS,</if>
<if test="createdBy != null">CREATED_BY,</if>
CREATED_TS,
<if test="lastUpdBy != null">LAST_UPD_BY,</if>
LAST_UPD_TS,
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
SYS_GUID(),
<if test="title != null">#{title,jdbcType=VARCHAR},</if>
<if test="content != null">#{content,jdbcType=VARCHAR},</if>
<if test="noticeStatus != null">#{noticeStatus,jdbcType=VARCHAR},</if>
<if test="createdBy != null">#{createdBy,jdbcType=VARCHAR},</if>
systimestamp,
<if test="lastUpdBy != null">#{lastUpdBy,jdbcType=VARCHAR},</if>
systimestamp,
</trim>
</insert>
大家可以自行理解一下。
最新文章
- context上下文 php版解释
- spark优化
- 【应用笔记】【AN004】VB环境下基于RS-485的4-20mA电流采集
- (转)【Android测试工具】03. ApkTool在Mac上的安装和使用(2.0版本)
- 1.单一职责原则(Single Responsibility Principle)
- Android 换肤功能的实现(Apk插件方式)
- js template
- 让jquery easyui datagrid列支持绑定嵌套对象
- Apache2 MPM 模式了解
- Apache Mina入门实例
- JVM垃圾回收机制概述
- 移动端h5 实现多个音频播放
- 11、Grafana 5.0 新功能特性(译文)
- Maven配置国内镜像仓库
- HDU 2089 不要62 【数位dp】
- Beta阶段第五次冲刺
- CF1096D Easy Problem(DP)
- Python3.5爬取cbooo.cn数据并且同步到mysql中
- GTK 预置对话框 GtkDialog 文件/颜色/字体选取等 GtkFileSelection
- std::async