Mybatis之动态SQL

liqiancao 2014-07-23

        MyBatis的动态SQL(Dynamic SQL)是基于强大的OGNL表达式,在操作SQL语句条件连接时可以帮助我们方便地实现某些逻辑。用于实现动态SQL的元素主要有:

  • if
  • choose(when,otherwise)
  • trim(where,set)
  • foreach

    1) if: 条件判断,利用if语句可以实现某些简单的条件选择。

        例如:可选地根据标题或者作者查询。


        <select id=”findActiveBlogWithIf” parameterType=”Blog” resultType=”Blog”>
                SELECT * FROM BLOG WHERE state = ‘ACTIVE’
                        <if test=”title != null”>
                                AND title like #{title}
                        </if>
                        <if test=”author != null and author.name != null”>
                                AND title like #{author.name}
                        </if>
        </select>

    2) choose:作用和java中的switch语句功能相似,都是when和otherwise配合使用。

        例如:只搜索有提供查询标题或只搜索有提供查询作者的数据。

                   如果两者都没有提供,那只返回加精的 Blog 。
 
        <select id=”findActiveBlogWithChoose” parameterType=”Blog” resultType=”Blog”>
                SELECT * FROM BLOG WHERE state = ‘ACTIVE’
                <choose>
                        <when test=”title != null”>
                                AND title like #{title}
                        </when>
                        <when test=”author != null and author.name != null”>
                                AND title like #{author.name}
                        </when>
                        <otherwise>
                                AND featured = 1
                        </otherwise>
                </choose>
        </select>

        注:当when中的条件满足的时候就输出其中的内容并跳出choose,跟JAVA中的switch效果差不多的是按照条件的顺序。即所有的when和otherwise条件中,只有一个会输出。当所有的很条件都不满足的时候就输出otherwise中的内容。
    
    3) where:简化SQL语句中where中的条件判断的。

        <select id=”findActiveBlogWithWhere” parameterType=”Blog” resultType=”Blog”>
               SELECT * FROM BLOG
               <where>
                        <if test=”state != null”>
                                state = #{state}
                        </if>
                        <if test=”title != null”>
                                AND title like #{title}
                        </if>
                        <if test=”author != null and author.name != null”>
                                AND title like #{author.name}
                        </if>
                </where>
        </select>


        注:它会在写入where元素的地方输出一个where,另外你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,如果 所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问 题,MyBatis会智能的加上。


    4) trim: 可以利用trim来代替where元素的功能。

        <select id=”findActiveBlogWithTrim” parameterType=”Blog” resultType=”Blog”>
                SELECT * FROM BLOG
                <trim prefix=”WHERE” prefixOverrides=”AND |OR”>
                        <if test=”state != null”>
                                state = #{state}
                        </if>
                        <if test=”title != null”>
                                 AND title like #{title}
                        </if>
                        <if test=”author != null”>
                                 OR title like #{author.name}
                        </if>
                 </trim>
        </select>

        注:可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides。

    5) set:用于更新操作。在包含的语句前输出一个 set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。

       <update id="updateAuthorWithSet" parameterType="domain.blog.Author">
               update Author
               <set>
                        <if test="username != null">
                                 username=#{username},
                        </if>
                        <if test="password != null">
                                 password=#{password},
                        </if>
                        <if test="email != null">
                                email=#{email},
                        </if>
                        <if test="bio != null">
                                bio=#{bio}
                       </if>
                 </set>
                         where id=#{id}
         </update>


    6) foreach:主要用于构建in条件中,它可以在SQL语句中进行集合迭代。属性主要有 item,index,collection,open,separator,close。
   item:表示集合中每一个元素进行迭代时的别名。
   index指定一个名字,用于表示在迭代过程中,每次迭代到的位置。
   open:表示该语句以什么开始。
   separator:表示在每次进行迭代之间以什么符号作为分隔符。
   close:表示以什么结束。
     collection:最关键的也是最容易出错的属性。该属性是必须指定的,但是在不同情况下,该属性的值是不一样的。主要有一下3种情况:
            1)如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
            2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
            3)如果传入的参数是多个的时候,需要把它们封装成一个Map。
        
    1.单参数List的类型:


        <select id=”dynamicWithForeachList” resultType=”Blog”>
                SELECT * FROM POST P WHERE ID in
                <foreach collection=”list” index=”index” item=”item” open=”(“ separator=”,” close=”)”>
                        #{item}
                </foreach>
        </select>


     上述collection的值为list,对应的Mapper是这样的:
            public List<Blog> dynamicWithForeachList(List<Integer> ids);

      测试代码:
     @Test
     public void dynamicWithForeachList() {
            SqlSession session = MybatisUtil.openSession();
            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            List<Integer> ids = new ArrayList<Integer>();
            ids.add(1);
            ids.add(2);
            ids.add(3);
            List<Blog> blogs = blogMapper.dynamicWithForeachList(ids);
            for (Blog blog : blogs)
                   System.out.println(blog);
            session.close();
    }

     2.单参数array数组的类型:


    <select id=”dynamicWithForeachArray” resultType=”Blog”>
            SELECT * FROM POST P WHERE ID in
            <foreach collection=”array” index=”index” item=”item” open=”(“ separator=”,” close=”)”>
                    #{item}
            </foreach>
    </select>


    上述collection为array,对应的Mapper代码:
         public List<Blog> dynamicWithForeachArray(int[] ids);
   

     测试代码:
     @Test
     public void dynamicWithForeachArray() {
            SqlSession session = MybatisUtil.openSession();
            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            int[] ids = new int[] {1,2,3};
            List<Blog> blogs = blogMapper.dynamicWithForeachArray(ids);
            for (Blog blog : blogs)
                    System.out.println(blog);
            session.close();
    }


    3.把参数封装成Map的类型

    <select id=”dynamicWithForeachMap” resultType=”Blog”>
            SELECT * FROM BLOG WHERE title like ”%”#{title}”%” and id in
            <foreach collection=”ids” index=”index” item=”item” open=”(“ separator=”,” close=”)”>
                  #{item}
            </foreach>
    </select>


    上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
          public List<Blog> dynamicWithForeachMap(Map<String, Object> params);

     测试代码:
     @Test
      public void dynamicWithForeachMap() {
            SqlSession session = MybatisUtil.openSession();
            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            final List<Integer> ids = new ArrayList<Integer>();
            ids.add(1);
            ids.add(2);
            ids.add(3);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(“ids”, ids);
            params.put(“title”, ”Mybatis实战”);
            List<Blog> blogs = blogMapper.dynamicWithForeachMap(params);
            for (Blog blog : blogs)
                    System.out.println(blog);
            session.close();
    }

相关推荐