mybatis学习笔记四
2024-09-07 06:20:19
记录下动态sql的常用标签:
1.where
一般用作数据操作添加的条件
例子:
<select id="selectByRoleId" resultMap="resource">
select * from resource
<where>
role_id = #{roleId}
</where>
2.if
一般用做查询,修改或者删除数据时的一些拼接条件。
test字段为判断条件
例子:
<select id="findCountByContditon" resultType="int" parameterType="com.example.demo.po.User">
select
coalesce(count(id),0)
from user
<where>
<if test="name != null and name != ''">
name like #{name}
</if>
<if test="createTime != null">
and create_time < #{createTime}
</if>
</where>
</select>
上面的sql有个问题,就是如果name条件不成立,creatTime条件成立,那么sql会报错。一般如果在where条件下有多个if判断,在if前加入where 1=1。
<select id="findCountByContditon" resultType="int" parameterType="com.example.demo.po.User">
select
coalesce(count(id),0)
from user
<where>
1=1
<if test="name != null and name != ''">
and name like #{name}
</if>
<if test="createTime != null">
and create_time < #{createTime}
</if>
</where>
</select>
3.foreach
一般用来批量添加数据
collection字段一般为list、array、map类型,值为传入的参数
separator字段值为分隔符,即以什么来分割
item 字段为循环时每个元素的别名
index 字段值为每次循环时的下标
open 字段值为前缀值
close 字段值为后缀值
例子:
<insert id="saveAll" parameterType="java.util.List">
insert into user(name,role_id,password)
values
<foreach collection="users" separator="," item="user" index="index" >
( #{user.name}, #{user.roleId}, #{user.password})
</foreach>
</insert>
4.set
一般用在修改数据,与if经常一起出现
<update id="updateByCondition">
update user
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="createTime != null">
create_time = @{createTime}
</if>
</set>
where id = #{id}
</update>
5.include
一般是将常用的字段抽出来作为常量
<sql id="user_columns">
id, name,role_id,password,create_time,update_time
</sql>
<select id="selectById" resultMap="user">
select
<include refid="user_columns"/>
from user where id = #{id}
</select>
6.trim
prefix字段前缀添加值
suffix字段后缀添加值
prefixOverrides字段删除前缀值
suffixOverrides字段删除后缀值
<update id="updateByCondition">
update user set
<trim suffixOverrides=",">
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="createTime != null">
create_time = @{createTime},
</if>
</trim>
where id = #{id}
</update>
如果password为空,其他不为空。sql变为
update user set name = #{name}, create_time = #{createTime} where id = #{id }
来源:http://www.1994july.club/seo/
最新文章
- 深入理解numpy
- NLog配置文件根节点
- 【转】TCP协议中的三次握手和四次挥手(图解)
- unity3d快捷键大全
- 原生js解决跨浏览器兼容问题
- Android4.0 -- UI控件之 Menu 菜单的的使用(四)
- ie8 hack
- 使用QGIS将文本坐标转换为矢量文件
- Pocket Gem OA: Path Finder
- linux下使用iptables统计ip/端口流量
- Redis(3)---Redis事务
- python学习笔记(七)- 递归、python内置函数、random模块
- [转]Jboss基础
- Oracle 导出错误 EXP-00000~EXP-00107
- GNU make简介
- SpringBoot(七)-- 启动加载数据
- RAC的搭建(二)--创建ASM磁盘
- shell脚本-监控及邮件提醒
- http的报文结构和状态码的含义
- JVM与外界通过数据通道进行数据交换