一、choose(when,otherwise)
1、说明
有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default
2、语法结构
<select..>
SQL语句1
<choose>
<when test="条件表达式">
SQL语句2
</when>
<otherwise>
SQL语句3
</otherwise>
</choose>
</select>
3、栗子
<resultMap id="BaseResultMap" type="User">
<id column="uid" jdbcType="INTEGER" property="uid" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="join_date" jdbcType="TIMESTAMP" property="joinDate" />
<result column="login_date" jdbcType="TIMESTAMP" property="loginDate" />
<result column="status" jdbcType="TINYINT" property="status" />
</resultMap>
<sql id="Base_Column_List">
`uid`, `name`, `password`, phone, email, join_date, login_date, `status`
</sql>
<select id="findUserChoose" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM user u
<where>
<choose>
<when test="user.name != null and user.name != '' ">
u.name LIKE CONCAT(CONCAT('%', #{user.name}),'%')
</when>
<when test="user.phone != null and user.phone != '' ">
AND u.phone = #{user.phone}
</when>
<when test="user.email != null and user.email != ''">
AND u.email = #{user.name,jdbcType=VARCHAR}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
网友评论