美文网首页mybatis
【mybatis】之三:动态SQL

【mybatis】之三:动态SQL

作者: 蛋花汤汤 | 来源:发表于2019-01-29 11:01 被阅读0次

一、标签提前看

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

    本文链接:https://www.haomeiwen.com/subject/kvicfqtx.html