一、if标签;携带了哪个字段查询条件就带上这个字段的值
语法:
<select id="getUsersByConditionIf" resultType="com.yjr.mybatis.bean.User">
select * from tb_user
<where>
<if test="name!=null and name!='' ">
and name like #{name}
</if>
<if test="lastName!=null and lastName!='' ">
and lastName = #{lastName}
</if>
</where>
</select>
二、choose (when, otherwise):分支选择;如果带了id就用id查,如果带了name就用name查;只会进入其中一个
select id="getUsersByConditionChoose" resultType="com.yjr.mybatis.bean.User">
select * from tb_User
<where>
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="name!=null">
name like #{name}
</when>
<otherwise>
1 = 1
</otherwise>
</choose>
</where>
</select>
三、set(封装修改条件)
<update id="updateUser">
update tb_user
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="email!=null">
email=#{email},
</if>
</set>
where id = #{id}
</update>
四、foreach遍历;
collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素
<select id="getUsersByConditionForeach" resultType="com.yjr.mybatis.bean.User">
select * from tb_user
<foreach collection="ids" item="item_id" separator=","
open="where id in(" close=")">
#{item_id}
</foreach>
</select>
五、批量保存
<insert id="addUser">
insert into tb_user(name,email)
values
<foreach collection="users" item="user" separator=",">
(#{user.name},#{user.email})
</foreach>
</insert>