Mybatis使用之动态SQL语句

Mybatis使用之动态SQL语句

 

一:简介

 

        Mybatis动态SQL语句可帮助我们根据需要动态拼接SQL语句。主要在配置文件中使用<where> <if><choose><when><otherwise> <set> <trim><foreach>标签来实现。

 

二:具体使用方式

 

       2.1 where

 

              2.1.1 功能

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

 

              2.1.2 映射文件配置:

    <select id="getBlogByConditionDynamic" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id
        <where>
            <if test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </if>
            <if test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </if>
        </where>
    </select>

              2.1.3 映射接口方法:

    List<Blog> getBlogByConditionDynamic(@Param("title") String title, @Param("section") String section);

              2.1.4 测试方法:

 

    @Test
    public void testGetBlogByConditionDynamic() throws Exception {
        List<Blog> blogList = blogMapper.getBlogByConditionDynamic("", "section");
        Assert.assertNotNull(blogList);
    }

       3.1 if

 

              3.1.1 功能

              简单的条件判断,利用if语句我们可以实现某些简单的条件选择。判断为则拼接、否则忽略。

              3.1.2 映射文件配置:

    <select id="getBlogDynamic" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id where 1=1
        <if test="title != null and title !=''">
            and t1.title like '%'||#{title}||'%'
        </if>
        <if test="section != null and section != ''">
            and t2.section like '%'||#{section}||'%'
        </if>
    </select>

              3.1.3 映射接口方法:

    List<Blog> getBlogDynamic(@Param("title") String title, @Param("section") String section);

              3.1.4 测试方法:

public class BlogMapperTest {

    private BlogMapper blogMapper;

    public BlogMapperTest() {
        blogMapper = MybatisUtil.getSqlSession().getMapper(BlogMapper.class);
    }

    @Test
    public void testGetBlogDynamic() throws Exception {
        List<Blog> blogList = blogMapper.getBlogDynamic("title", "section");
        Assert.assertNotNull(blogList);
    }

              

             

       4.1 choose


        4.1.1 功能

              choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时 候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的 内容。

              4.1.2 映射文件配置:

    <select id="getBlogByTitleOrSection" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id where 1=1
        <choose>
            <when test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </when>
            <when test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </when>
            <otherwise>
                and t1.title is not null and t2.section is not null
            </otherwise>
        </choose>
    </select>

              4.1.3 映射接口方法:

    List<Blog> getBlogByTitleOrSection(@Param("title") String title, @Param("section") String section);

              4.1.4 测试方法:

 

    @Test
    public void testGetBlogByTitleOrSection() throws Exception {
        List<Blog> blogList = blogMapper.getBlogByTitleOrSection("", "");
        Assert.assertNotNull(blogList);
    }

              5.1 set

 

                     5.1.1 功能

                     set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。

                     5.1.2 映射文件配置:

    <update id="updateBlogTitleSet" parameterType="blog">
        update blog
        <set>
            <if test="title != null and title != ''">
                 title = #{title}
            </if>
            <if test="id != null and id != ''">
                , id = #{id}
            </if>
        </set>
        where id = #{id}
    </update>

                     5.1.3 映射接口方法:

    int updateBlogTitleSet(Blog blog);

                     5.1.4 测试方法:

 

    @Test
    public void testUpdateBlogTitleSet() throws Exception {
        Blog blog = new Blog(1, "");
        int flag = this.blogMapper.updateBlogTitleSet(blog);
        Assert.assertEquals(true, flag > 0);
    }

       6.1 trim

 

                     6.1.1 功能

                     trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是 prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和 suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能

                     6.1.2 映射文件配置:

    <select id="getBlogByConditionDynamicTrim" resultMap="oneToManyNested">
        select t1.id blog_id, t1.title, t2.id post_id, t2.section
        from blog t1 left outer join post t2 on t1.id = t2.blog_id
        <trim prefix="where" prefixOverrides="and | or">
            <if test="title != null and title !=''">
                and t1.title like '%'||#{title}||'%'
            </if>
            <if test="section != null and section != ''">
                and t2.section like '%'||#{section}||'%'
            </if>
        </trim>
    </select>

                     6.1.3 映射接口方法:

    List<Blog> getBlogByConditionDynamicTrim(@Param("title") String title, @Param("section") String section);

                     6.1.4 测试方法:

 

    @Test
    public void testGetBlogByConditionDynamicTrim() throws Exception {
        List<Blog> blogList = blogMapper.getBlogByConditionDynamicTrim("title", "section");
        Assert.assertNotNull(blogList);
    }

       7.1 foreach

 

              7.1.1 功能

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

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

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

如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

 以Array为例:

              7.1.2 映射文件配置:

	<select id="dynamicForeach2Test" resultType="Blog">
		select * from t_blog where id in
		<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</select>

              7.1.3 映射接口方法:

public List<Blog> dynamicForeach2Test(int[] ids);

              7.1.4 测试方法:

	@Test
	public void dynamicForeach2Test() {
		SqlSession session = MybatisUtil.getSqlSessionFactory().openSession();
		BlogMapper blogMapper = session.getMapper(BlogMapper.class);
		int[] ids = new int[] {1,3,6,9};
		List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
	}

三:补充


        更多内容:Mybatis 目录

        github地址:https://github.com/andyChenHuaYing/scattered-items/tree/master/items-mybatis

        源码下载地址:http://download.csdn.net/detail/chenghuaying/8713311

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。