动态SQL元素包括 if \ choose(when \ otherwise) \where \ set \foreach \bind
1.if
<select id="selectUsers" resultType="User">
select * from users where state = 1
<if test="id != null"> 如果传入了id 参数,则加条件
and id = #{id}
</if>
</select>
对应的接口要进行相应设置
selectUsers(HashMap<String , Object>); //HashMap 中包含id 来判断,也可以从javabean 中获取 property对象
多条件组合:
<if test="id != null and name != null ">
and id = #{id} and name = #{name}
</if>
2.choose(when \ otherwise)
<choose>
<when test="id != null">
and id = #{id}
</when>
<otherwise>
and sex = 'male'
</otherwise>
</choose>
对应接口的设置形式,和if一样。
3.where ,为组装条件,会自动对 连接符 进行舍去,避免组装的SQL 报错。
select * from users
<where>
<if test="state != null">
state = #{state}
</if>
<if test="id != null">
id = #{id}
</if>
</where>
4.set ,主要用于需更新的列
<update id="user" parameterType="User">
update User
<set>
<if test="name != null">name=#{name}</if>
<if test="sex != null">sex=#{sex}</if>
</set>
where id=#{id}
</update>
5.foreach
select * from User where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
对应接口使用,list作为参数。
6.bind
<bind name="pattern" value="'%' + _parameter.getName() +'%'" />
SELECT * FROM User Where name like #{pattern}