Mybatis动态SQL

xml配置文件(只写了主要部分):

 
  <!--  动态sql -->
  <!--  动态更新用户信息,注意用于判断时标点符号的注意-->
  <!--  <set>会根据相应的消除无关的逗号-->
  <update id="DynamicUpdateStu" parameterType="Student">
    update student 
    <set>
        <if test="username !=null">username=#{username},</if>
         <if test="password !=null">password=#{password},</if>
        <if test="clazznumber !=null">clazznumber=#{clazznumber},</if>
        <if test="clazzname !=null">clazzname=#{clazzname},</if>
        <if test="sex !=null">sex=#{sex},</if>
          <if test="address !=null">address=#{address},</if>
          <if test="email !=null">email=#{email},</if>
        <if test="phone !=null">phone=#{phone},</if>
        <if test="flag !=null">flag=#{flag},</if>
    </set>
    where id=#{id}
    </update>
    <!-- 动态查询用户信息,返回可以是一个集合 -->
    <select id="DynamicSelectStu" parameterType="hashmap" resultType="Student">
        select * from student where flag=1
        <choose>
            <when test="id !=null">and id = #{id}</when>
            <when test="username != null"> and username = #{username}</when>
            <otherwise>
                and sex = 1
            </otherwise>
        </choose>
    </select>
    <!-- 方法二,防止为传入参数查询报错 -->
    <!-- 使用<where>防止未传入参数报错 -->
    <select id="DynamicSelectStu2"  parameterType="hashmap" resultType="Student">
        select * from student
        <where>
            <if test="id !=null"> id=#{id}</if>
            <if test="username !=null"> username=#{username}</if>
            <if test="flag !=null"> flag=#{flag}</if>
        </where>
    </select>
    <select id="DynamicSelectStuIn" resultType="Student">
        select * from student where  id in
        <foreach item="item" index="index" collection="list" 
            open="(" separator="," close=")" >
            #{item}
        </foreach>
    </select>
    <!-- bind模糊查询 -->
    <select id="DynamicSelectStuLikeName" parameterType="Student"    resultType="Student">
        <bind name="pattern" value="'%' + _parameter.getUsername() +'%'"/>
            select * from student where username like #{pattern}
    </select>

 

posted @ 2019-10-20 18:55  Cool_Yang  阅读(166)  评论(0编辑  收藏  举报