Mysql-Mybatis常用动态Sql语句

1.<if>

<select id="" parameterType="" resultType="">  
    select * from user where 1 = 1  
    <if test="username != null">  
        and username = #{username}  
    </if>  
    <if test="userCode != null">  
        and user_code = #{userCode}  
    </if>   
</select>

2.<choose>

<select id="" parameterType="" resultType="">  
    select * from user where 1 = 1   
    <choose>  
        <when test="username != null">  
            and username = #{username}  
        </when>  
        <when test="userCode != null">  
            and user_code = #{userCode}  
        </when>  
        <otherwise>  
            and user_id = "1"  
        </otherwise>  
    </choose>  
</select>

  相当于Java中的switch语句,当满足when中条件时即执行相应内容,都不满足则执行otherwise中的内容; 它是按顺序执行,只要when中只要满足一条即刻跳出choose,即:所有的when和otherwise条件中只满足一条.

3.<where>

<select id="" parameterType="" resultType="">  
    select * from user   
    <where>  
        <if test="username != null">  
            username = #{username}  
        </if>  
        <if test="userCode != null">  
            and user_code = #{userCode}  
        </if>  
    </where>  
</select>

4.<trim>

<select id="" parameterType="" resultType="">  
    select * from user   
    <trim prefix="where" prefixOverrides="and |or">  --添加前缀where   去掉第一个and或者or
        <if test="username != null">  
            username = #{username}  
        </if>  
        <if test="userCode != null">  
            and user_code = #{userCode}  
        </if>  
    </trim>  
</select>

  可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;

  可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;

  trim的此功能,我们可以非常简单的利用trim来代替where元素的功能.

5.<set>

<update id="" parameterType="">  
    update user  
    <set>  
        <if test="username != null">  
            username = #{username},  
        </if>  
        <if test="userCode != null">  
            user_code = #{userCode},  
        </if>  
    </set>  
    where user_id = #{userId}  
</update>

  用于更新操作;

  如果包含的语句是以逗号结束的话将会把该逗号忽略;

  如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错.

6.<foreach>

<select id="" resultType="">  
    select * from user where user_id in  
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
</select>

  item表示集合中每一个元素进行迭代时的别名;

  index指定一个名字,用于表示在迭代过程中,每次迭代到的位置;

  open表示该语句以什么开始;

  separator表示在每次进行迭代之间以什么符号作为分隔符;

  close表示以什么结束;

  在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,

  该属性的值是不一样的:

    -如果传入的是单参数且参数类型是一个List的时候,collection属性值为list;

    -如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array;

    -如果传入的参数是多个的时候,把它们封装成一个Map了,当然单参数也可以封装成map,

      实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,

      所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

posted @ 2022-02-07 10:46  静沐丶暖阳  阅读(289)  评论(0编辑  收藏  举报