1.前缀和忽略前缀用于查询数据库代码
//prefix前缀 prefixOverrides忽略前缀 <select id="getlist" resultType="com.xinxi2.bean.TSysUser"> SELECT * FROM `t_sys_user` <trim prefix="where" prefixOverrides="and|or"> <if test="realname!=null"> and realname=#{realname} </if> <if test="password!=null"> and password=#{password} </if> <if test="acccunt!=null"> and acccunt=#{acccunt} </if> </trim> </select>
2.后缀和忽略后缀用于修改数据库代码
//suffix后缀 suffixOverrides忽略后缀 <update id="update" parameterType="com.xinxi2.bean.TSysUser"> update t_sys_user <trim suffix="set" suffixOverrides=","> <if test="realname!=null"> realname=#{realname}, </if> <if test="password!=null"> password=#{password}, </if> <if test="acccunt!=null"> acccunt=#{acccunt}, </if> </trim> where id=#{id} </update>
where标签
where标签的主要作用是对SQL语句中的where关键字进行简化处理,并可以智能地处理其内部and、or等关键字
/*TSysUserMapper.xml*/ <select id="getlist" resultType="com.xinxi2.bean.TSysUser"> SELECT * FROM `t_sys_user` <where> <if test="realname!=null"> and realname=#{realname} </if> <if test="password!=null"> and password=#{password} </if> <if test="acccunt!=null"> and acccunt=#{acccunt} </if> <if test="id!=null"> and id=#{id} </if> </where> </select>
set标签
MyBatis 提供了 set 元素,set 元素主要用于修改操作,它可以在动态 SQL 语句前输出一个 SET 关键字,并将 SQL 语句中最后一个多余的逗号去掉,set 元素与 if 元素结合可以实现只修改需要更新的字段
/*TSysUserMapper.xml*/ <update id="update" parameterType="com.xinxi2.bean.TSysUser"> update t_sys_user <set> <if test="realname!=null"> realname=#{realname}, </if> <if test="password!=null"> password=#{password}, </if> <if test="acccunt!=null"> acccunt=#{acccunt}, </if> </set> where id=#{id} </update>
foreach标签
循环标签 适用于批量添加、删除 和查询记录
collection | 必填,指定参数入参类型 列表(list) 、数组(array)、HashMap(map) |
item | 起名字,给集合中单个元素起名称 |
open | 开始字符串 |
close | 结束字符串 |
separator | 分割符 |
index | 索引的属性名,在集合数组下值为当前的索引值 |
1.foreach 元素迭代数组
//单参数List的类型 /*TSysUserMapper.xml*/ <select id="getlist" resultType="com.xinxi2.bean.TSysUser"> SELECT * FROM `t_sys_user` <where> id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach> </where> </select>
2.foreach 元素迭代 List
//数组类型的参数 /*TSysUserMapper.xml*/ <select id="getlist" resultType="com.xinxi2.bean.TSysUser"> SELECT * FROM `t_sys_user` <where> id in <foreach collection="array" item="id" open="(" close=")" separator=","> #{id} </foreach> </where> </select>
3.foreach 元素迭代 Map
//Map类型参数 /*TSysUserMapper.xml*/ <select id="getlist" resultType="com.xinxi2.bean.TSysUser"> SELECT * FROM `t_sys_user` <where> id in <foreach collection="array" item="item" open="(" close=")" separator=","> #{item} </foreach> </where> </select>