1、if
if元素可以用于根据条件判断是否包含某个SQL语句片段。
<!--查询年龄大于18岁且小于等于30岁的用户信息:<if>元素用于判断minAge和maxAge是否为null,如果不为null,则将对应的SQL语句片段拼接到最终的SQL语句中
-->
<select id="findUsersByAge" parameterType="Map" resultType="User">SELECT *from userWHERE 1 = 1<if test="minAge != null">AND age >= #{minAge}</if><if test="maxAge != null">AND age <= #{maxAge}</if>
</select>
2、where元素
where元素可以用于动态生成where子句,如果所有条件均为null,则不会生成where子句。
<!--查询用户名和密码匹配的用户信息:<where>元素用于动态生成where子句,如果username和password均为null,则不会生成where子句
-->
<select id="findUserByUsernameAndPassword" parameterType="Map" resultType="User">SELECT *FROM user<where><if test="username != null">AND username = #{username}</if><if test="password != null">AND password = #{password}</if></where>
</select>
3、foreach
foreach元素可以用于循环遍历一个集合,并将集合中的元素拼接到SQL语句中。
<!-- 查询多个用户信息:<foreach>元素用于循环遍历List类型的参数,并将集合中的元素拼接到SQL语句中
-->
<select id="findUsersByIds" parameterType="List" resultType="User">SELECT *FROM userWHERE id IN<foreach collection="list" item="id" open="(" separator="," close=")">#{id}</foreach>
</select>
4、choose(when、otherwise)
choose 相当于 java 里面的 switch 语句。otherwise(其他情况)
<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG WHERE state = ‘ACTIVE’<choose><when test="title != null">AND title like #{title}</when><when test="author != null and author.name != null">AND author_name like #{author.name}</when><otherwise>AND featured = 1</otherwise></choose>
</select>
5、trim
prefix:前缀prefixoverride:去掉第一个and或者是or
select * from test
<trim prefix="WHERE" prefixoverride="AND丨OR"><if test="a!=null and a!=' '">AND a=#{a}<if><if test="b!=null and b!=' '">AND a=#{a}<if>
</trim>
6、set
set 元素主要是用在更新操作的时候,如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。
<update id="dynamicSetTest" parameterType="Blog"> update t_blog <set> <if test="title != null"> title = #{title}, </if> <if test="content != null"> content = #{content}, </if> <if test="owner != null"> owner = #{owner} </if> </set> where id = #{id}
</update>