【mybatis】之三:动态SQL

一、标签提前看

mybatis中,提供了如下几种标签用来完成动态语句的拼接。

  • if
  • choose/when/otherwise
  • trim/where/set
  • foreach

二、使用

  • if标签
    <select id="getEmployeeByConditionIf" resultType="com.hly.entity.Employee">
        SELECT *
        FROM tbl_employee
        <where>
            <!--<if test="id!=null">-->
                <!--id=#{id}-->
            <!--</if>-->
            <if test="name!=null">
                and name=#{name}
            </if>
            <if test="email!=null">
                and email=#{email}
            </if>
            <if test="gender!=null">
                and gender=#{gender}
            </if>
        </where>
    </select>

在这里直接使用了where标签。where标签可以帮我们处理拼接时可能产生的语句一场情况,这里主要是where后直接跟and或者or的情况。这种用法应该比较多。

  • choose标签
    <select id="getEmployeeByConditionChoose" resultType="com.hly.entity.Employee">
        SELECT *
        FROM tbl_employee
        WHERE 
        <choose>
            <when test="name!=null">
                name like #{name}
            </when>
            <when test="email!=null">
                <bind name="pattern" value="'%'+ _parameter.getEmail() +'%'"></bind>
                email like #{pattern}
            </when>
            <when test="gender!=null">
                gender like #{gender}
            </when>
            <otherwise>
                1=1
            </otherwise>
        </choose>
    </select>

choose/when/otherwise有点像java里面的switch-case-default的用法,不同的是,众多分支语句中,只会走其中一条语句。在这个案例中,还使用到了bind标签。这个标签的作用是从OGNL标签中创建一个变量,并将其绑定到上下文。稳重这种用法应该是比较典型的一种应用,不想sql的查询(like)逻辑侵入到业务实体对象中,采用这种方式可以实现比较好的分离。

  • set标签
    trim在这里不演示了,有了where,应该可以覆盖绝大多数的场景。
    <update id="updateEmployeeById">
        UPDATE tbl_employee
        <set>
            <if test="name!=null">
                name=#{name},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </set>
        WHERE id=#{id}
    </update>

这个比较直接和简单,在set标签下多个if条件,哪个不为空就更新哪个字段的值。

  • foreach标签
    <select id="getEmpsInIds" resultType="com.hly.entity.Employee">
        SELECT *
        FROM tbl_employee
        WHERE id IN
        <foreach collection="list" item="item" index="index"
                 open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

foreach标签主要用于in语句,测试代码如下:

@Test
    public void testConditionForeach(){
        SqlSession sqlSession = null;
        try{
            sqlSession = getSession();
            List<Integer> list = new ArrayList<Integer>();
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            EmployeeConditionMapper employeeConditionMapper = sqlSession.getMapper(EmployeeConditionMapper.class);
            List<Employee> emps = employeeConditionMapper.getEmpsInIds(list);
            for (Employee e: emps) {
                System.out.println(e);
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally{
            sqlSession.close();
        }
    }

设置一个list列表,用来存储id列表,调用所写方法,得到如下执行结果:

DEBUG [main] - ==>  Preparing: SELECT * FROM tbl_employee WHERE id IN ( ? , ? , ? , ? ) 
DEBUG [main] - ==> Parameters: 1(Integer), 2(Integer), 3(Integer), 4(Integer)
DEBUG [main] - <==      Total: 2
Employee{id=1, name='Lingyu He', gender='1', email='hhh@webank.com'}
Employee{id=4, name='John He1122', gender='1', email='1@webank.com'}

可以看到,查询成功,in里面拼装了4个参数,小括号开始和收尾,以逗号为分隔符。
再来看使用foreach标签进行批量插入的例子。

    <insert id="batchAddEmps">
        INSERT INTO tbl_employee VALUES
        <foreach collection="list" item="emp" separator=",">
            (null, #{emp.name},#{emp.gender},#{emp.email},#{emp.department.id})
        </foreach>
    </insert>

结果如下:

DEBUG [main] - ==>  Preparing: INSERT INTO tbl_employee VALUES (null, ?,?,?,?) , (null, ?,?,?,?) 
DEBUG [main] - ==> Parameters: test1(String), 1(String), aaa@163.com(String), 1(Integer), test2(String), 0(String), bbb@163.com(String), 1(Integer)
DEBUG [main] - <==    Updates: 2

可以看到语句封装成功,执行也成功。

三、总结

这一节干货不多,主要是一些为了拼接动态sql语句的标签,实用性比较多,需要在实际应用中灵活选择要使用的标签组合。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • MyBatis 动态SQL 内容 Mybatis动态SQL在XML中支持的几种标签: if chose trim、...
    lihongyan阅读 8,412评论 1 10
  • if if 标签通常用于 WHE阻 语句中,通过判断参数值来决定是否使用某个查询条件,它也经常用于 UPDATE ...
    miye阅读 621评论 0 0
  • MyBatis动态SQL 前言 在前面,我们已经学习了MyBatis的单表操作以及多表操作,在体验了MyBatis...
    颜洛滨阅读 1,766评论 2 47
  • 当我们使用传统JDBC方法去写复杂的SQL语句的时候,需要去进行大量的拼接。常常会因为一个小错误如少写了一个空格导...
    其实我很菜啊阅读 1,175评论 0 2
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,677评论 0 4