MyBatis---动态 SQL
1.if
2.choose, when, otherwise
3. where
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> </where> </select>
4.set
<update id="updateAuthor"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> </set> where id=#{id} </update>
5.trim
select * from user <trim prefix="WHERE" prefixoverride="AND |OR"><!--prefixoverride:去掉第一个and或者是or--> <if test="name != null and name.length()>0"> AND name=#{name}</if> <if test="gender != null and gender.length()>0"> AND gender=#{gender}</if> </trim>
假如说name和gender的值都不为null的话打印的SQL为:select * from user where name = 'xx' and gender = 'xx'
update user <trim prefix="set" suffixoverride="," suffix=" where id = #{id} "><!--suffixoverride:去掉最后一个逗号;suffix:后缀--> <if test="name != null and name.length()>0"> name=#{name} , </if> <if test="gender != null and gender.length()>0"> gender=#{gender} , </if> </trim>
假如说name和gender的值都不为null的话打印的SQL为:update user set name='xx' , gender='xx' where id='x'
6.foreach
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>