Mybatis查询 动态sql

Mybatis查询 动态sql

  • < sql > and < include >

    <sql id="allColumns"> id ,username,birthday,sex,address</sql>
    
    <select id="方法名" resultType="users">
    	select <include refid="allColumns"></include>
        from users
    </select>
    
  • < if > and < where >

    <select id="方法名" resultType="users">
    	select <include refid="allColumns"></include>
        from users
        <where>
        	<if test="userName != null and username ="">
    			and username like concat('%'#{username}'%')
            </if>
            <if  test="birthday != null and birthday ="">
                and birthday like concat('%'#{birthday}'%') 
            </if>                                           
        </where>
    </select>           	
    
  • < set > 为空的不更新

    <select id="方法名" resultType="users">
    	select <include refid="allColumns"></include>
        from users
        <where>
            <set>
                <if test="userName != null and username ="">
    				and username like concat('%'#{username}'%')
            	</if>
                <if  test="birthday != null and birthday ="">
                	and birthday like concat('%'#{birthday}'%') 
            	</if> 
            </set>
        </where>
    </select>       
    
  • < foreach > 循环遍历 循环条件查询 删除 增加 更改

    <select id="方法名" resultType="users">
    	select <include refid="allColumns"></include>
        from users
        <where>  id in
            <foreach collection="array" item="id" separator="," open="(",close=")">
        		#{id}
        	</foreach>
        </where>
    </select>  
    
    • 详解

      • collection:用来指定入参的类型,如果是List集合,则为list,如果为Map集合,则为map,如果是数组,则为array,
      • item:每次循环遍历出来的值或对象
      • separator:多个值或对象或者语句之间的分隔符
      • open:整个循环外的前括号 close:整个循环外面的后括号

posted @ 2022-04-01 15:48  Tian-Jotian-Yongxing  阅读(135)  评论(0)    收藏  举报