mybatis入门篇:mybatis动态SQL

时间:2023-03-08 16:38:51

1、if用法

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    where 1=1
    <if test="userName != null and userName != '' ">
        and user_name like concat('%', #{userName}, '%')
    </if>
    <if test="userPhone != null and userPhone !='' ">
        and user_phone=#{userPhone}
    </if>
</select>

2、choose

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    where 1=1 /*此处不可忽略*/
    <choose>
        <when test="id != null">
            and id=#{id}
        </when>
        <when test="userName != null and userName !='' ">
            and user_name=#{userName}
        </when>
        <otherwise>
            and 1=2 /*此处不可忽略*/
        </otherwise>
    </choose>
</select>

 3、where

where标签内如果没有符合条件的选项,则最后生成的sql语句不含where;如果有符合条件的,则生成的sql语句会自动去除两端的and

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    <where>
        <if test="userName != null and userName != '' ">
        and user_name like concat('%', #{userName}, '%')
        </if>
        <if test="userEmail != null and userEmail != '' ">
        and user_email = #{userEmail}
        </if>
    </where>
</select>

 4、set

<update id="updateUserById">
    update user
    <set>
        <if test="userName != null and userName != '' ">
        user_name=#{userName},
        </if>
        id=#{id}  /*此处不可忽略*/
    </set>
    where id=#{id}
</update>

 5、foreach

collection:必填,值为要迭代循环的属性名。

item:变量名,值为要从迭代对象中取出的每一个值

index:索引的属性名。在集合数组下为索引值,在Map对象下为Map的key值。

参数为List的情况

<select id="selectByIdList" resultType="com.forest.owl.entity.User">
    select * from user
    where id in
    <foreach collection="list" open="(" close=")" separator="," item="id" index="i">
    #{id}
    </foreach>
</select>

参数为Map的情况

    <update id="updateByMap">
        update user
        set
        <foreach collection="_parameter" item="val" index="key" separator=",">
            ${key}=#{val}
        </foreach>
        where id=#{id}
    </update>

6、bind

bind标签可以使用OGML表达式创建一个变量病绑定到上下文中。

<if test="userName != null and userName != '' ">
and user_name like concat('%', #{userName}, '%')
</if>

可以通过bind改写成

<if test="userName != null and userName != '' ">
    <bind name="userNameLike" value=" '%' + userName + '%' "/>
    and user_name #{userNameLike}
</if>

7、如果测试的时候想知道映射XML中方法执行的参数 可以这么做:

public class StringUtil{
    public static void print(Object parameter){
        System.out.println(parameter);
    }
}
<bind name="print" value="@com.forest.owl.util.StringUtil@print(_parameter)" />

 8、鉴别器映射(discriminator)

有时单独一个映射会需要返回不同数据类型的结果集,discriminator就是为了用来处理这种情况。

因为感觉这个标签不会很常用,所以不做进一步了解,暂时给出简单的代码,后续有需要再回来翻阅:

  <resultMap id="UserAndRole" extends="BaseResultMap" type="com.forest.owl.entity.User">
    <discriminator javaType="int" column="enabled">
      <" resultMap="resultMap1"/>
      <" resultMap="resultMap2"/>
    </discriminator>
  </resultMap>