- if test;
select * from user where <if test="id!=null and ''!=id"> id = #{id} </if> <!-- OGNL会自动进行字符串与数字间的转换 --> <if test="des == 0 or des == 1"> and des = #{des} </if>
缺点:当id字段为空时,sql条件语句中会出现多余的“and”,导致错误。
解决方法:①条件语句开头添加“1=1”。②mybatis用<where></where>标签江第一个多出来的and/or去除。 -
trim标签:自定义截取字符串;
select * from user <!-- 弥补where标签无法去除后面多出and/or的缺点。 prefix="":前缀:为字符串加一个前缀。 prefixOverrides="":前缀覆盖:去掉字符串前多余的字符。 suffix="":后缀:为字符串加一个后缀。 suffixOverrides="":后缀覆盖:去掉字符串后多余的字符。 --> <trim prefix="where" suffixOverrides="and"> <if test="id !=null and ''!=id"> id = #{id} and </if> <if test="des == 0 or des == 1"> des = #{des} </if> </trim>
- choose(when,otherwise):按顺序取条件查询,只会进入其中一个条件。
select * from user <where> <!-- 顺序至上而下,从第一个满足的条件进入 --> <choose> <when test="id != null and '' != id"> id = #{id} </when> <when test="name != null and '' != name"> name like #{name} </when> <otherwise> 1=1 </otherwise> </choose> <where>
- trim中的set标签(where,set)
update user <!-- set标签可以将字段后面的逗号去掉 --> <set> <if test="id!=null and ''!=id"> id = #{id}, </if> <if test="des!=null and ''!=des"> des = #{des}, </if> </set> where name = #{name}
上述代码也可用trim标签代替。
- foreach:遍历元素。对一个集合进行遍历,通常在in条件语句中使用。
select * from user where id in <!-- collection:指定要遍历的集合 item:将当前遍历出的元素赋值给指定的变量 separator:每个元素之间的分隔符 open:在结果前拼接一个开始的字符串 close:在结果后拼接一个结束的字符串 --> <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach>
foreach还可以用于批量保存数据
INSERT INTO user(name,age,email)VALUES <foreach collection="userList" item="user" separator=","> (#{user.name},#{user.age},#{user.eamil}) </foreach>
以上为个人学习笔记,读者没看明白的话可按着链接查看这位前辈的博文:
https://www.cnblogs.com/lc-java/p/7491693.html