动态sql
    利用动态 SQL,可以彻底摆脱动态拼接 sql 的痛苦
    ●if
    ●choose (when, otherwise)
    ●trim (where, set)
    ●foreach
    if + where 条件

    1. <!--姓名、密码动态查询,为空就是全查询-->
    2. <select id="find1" resultMap="usermap">
    3. select * from user where 1=1
    4. <if test="name!=null">
    5. and username = #{name}
    6. </if>
    7. <if test="password!=null">
    8. and password = #{password}
    9. </if>
    10. </select>

    改进写法,使用 where 标签,会智能的给我们添加 where 关键字,并且能智能的帮我们去掉 and

    1. <select id="find1" resultMap="usermap">
    2. select * from user
    3. <where>
    4. <if test="name!=null">
    5. and username = #{name}
    6. </if>
    7. <if test="password!=null">
    8. and password = #{password}
    9. </if>
    10. </where>
    11. </select>

    if + set 条件
    set 标签同样很智能,会帮我们智能的去掉最后的逗号

    1. <!--传什么参数就修改什么字段-->
    2. <update id="update">
    3. update user
    4. <set>
    5. <if test="name!=null">
    6. username = #{name},
    7. </if>
    8. <if test="age!=null">
    9. age = #{age},
    10. </if>
    11. <if test="address!=null">
    12. address = #{address},
    13. </if>
    14. <if test="password!=null">
    15. password = #{password},
    16. </if>
    17. </set>
    18. where id = #{id}
    19. </update>

    trim(基本上用不到了) ;
    属性
    ●prefix:加前缀
    ●prefixOverrides:去掉前缀
    ●suffix:加后缀
    ●suffixOverrides:去掉后缀

    1. <select id="find2" resultMap="usermap">
    2. select * from user
    3. <trim prefix="where" prefixOverrides="and">
    4. <if test="name!=null">
    5. and username = #{name}
    6. </if>
    7. <if test="password!=null">
    8. and password = #{password}
    9. </if>
    10. </trim>
    11. </select>
    1. <update id="update2">
    2. update user
    3. <trim prefix="set" suffixOverrides=",">
    4. <if test="name!=null">
    5. username = #{name},
    6. </if>
    7. <if test="age!=null">
    8. age = #{age},
    9. </if>
    10. <if test="address!=null">
    11. address = #{address},
    12. </if>
    13. <if test="password!=null">
    14. password = #{password},
    15. </if>
    16. </trim>
    17. where id = #{id}
    18. </update>