mybatis学习(七)(choose的学习)

在平时使用mapper配置的时候,如果有一个参数不确定它的状态导致sql不好写,那么可以使用choose来选择不同状态下的sql语句,

实例:

  根据deptno参数的有无来选择合适的sql语句:

mapper.xml配置如下:

  

<select id="select05" parameterType="Integer" resultType="Dept">
        <choose>
            <when test="_parameter != 0">
                select * from dept where deptno = #{_parameter}<!-- 当使用的是基本数据类型来传参数时,占位符使用_parameter -->
            </when>
            <otherwise>
                select * from dept
            </otherwise>
        </choose>
    </select>
    

这里关于choose还要提几点:

  when是条件选择,otherwise是其他条件, 一个choose里面可以有多个when,但只能有一个otherwise.

  当然,条条道路通罗马,要想完成上面的任务,不单单只有choose可以使用,你也可以使用where条件,只不过多掌握一个知识点,将来吹牛逼就不需要打草稿了。

原文地址:https://www.cnblogs.com/1998xujinren/p/11211805.html