<!--
SQL片段
sql标签,id属性:唯一标识,将来各个statement语句中通过include标签的refid属性将其引入
-->
<!--
1.1 if标签 test属性:布尔类型表达式
-->
<sql id="sql1">
<if test="user!=null">
<if test="user.gender!=null and user.gender!=''">
and gender=#{user.gender}
</if>
<if test="user.name!=null and user.name!=''">
and name like concat('%',#{user.name},'%')
</if>
</if>
</sql>
<!--
1.2 foreach标签 迭代标签
collection属性:列表名,例如:ids数组、List<User>集合等
index属性:索引值
item属性:迭代出的元素
open属性:拼接开始的符号
close属性:拼接结束的符号
separator属性:分隔符
-->
<!-- 方式一:and id in(13,17,22) -->
<sql id="sql2">
<if test="ids!=null">
<foreach collection="ids" item="id" open="and id in(" close=")" separator=",">
#{id}
</foreach>
</if>
</sql>
<!-- 方式二:and (id=13 or id=17 or id=23) -->
<sql id="sql2">
<if test="ids!=null">
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</if>
</sql>
<!--
1.需求:通过用户性别和姓名查询用户列表 PS:不允许性别或者姓名为null或者空串
动态sql:标签 if where foreach set choose&when&otherwise ...
where标签 充当where条件进行使用,默认去除第一个拼接上的条件的and
-->
<select id="findUserByGenderAndName" parameterType="UserQueryVO" resultType="User">
select * from user
<where>
<include refid="sql1" />
</where>
</select>
<!--
2.需求:通过用户性别和姓名查询用户列表,且id值是15或20或25 PS:不允许性别或者姓名为null或者空串
-->
<select id="findUsers" parameterType="UserQueryVO" resultType="User">
select * from user
<where>
<include refid="sql1" />
<include refid="sql2" />
</where>
</select>
<!-- 3.批量插入用户数据 -->
<insert id="insertUserBatch" parameterType="list">
insert into user(name,age,gender,birthday,pwd,state)
<foreach collection="list" item="user" open="values" close="" separator=",">
(#{user.name},#{user.age},#{user.gender},#{user.birthday},#{user.pwd},#{user.state})
</foreach>
</insert>
<!-- 4.更新用户的非空信息 -->
<update id="updateUser" parameterType="User">
update user
<set>
<if test="name!=null">
name=#{name}
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</set>
where state=#{state}
</update>