程序员的知识教程库

网站首页 > 教程分享 正文

MyBatis-动态SQL的if、choose、when、otherwise等使用

henian88 2024-09-09 03:42:16 教程分享 11 ℃ 0 评论

动态SQL是MyBatis最强大的特性之一。用于实现动态SQL的主要元素如下:

1、if

EmpMapper.xml配置

<select id="getEmpByIf" resultType="Emp" parameterType="Emp"> select * from emp where 1 = 1
 <if test="job != null and job != ''"> and job = #{job}
 </if>
 <if test="deptno != null "> and deptno = #{deptno}
 </if>
</select>

2、choose、when、otherwise

类似于Java中的switch case default

EmpMapper.xml配置

<select id="getEmpByChoose" resultType="Emp" parameterType="Emp"> select * from emp where 1 = 1
 <choose>
 <when test="job != null"> and job = #{job}
 </when>
 <when test="deptno != null"> and deptno = #{deptno}
 </when>
 <otherwise> and mgr = #{mgr}
 </otherwise>
 </choose>
</select>

3、where

EmpMapper.xml配置

<select id="getEmpByWhere" resultType="Emp" parameterType="Emp"> select * from emp
 <where>
 <if test="job != null and job != ''"> and job = #{job}
 </if>
 <if test="deptno != null"> and deptno = #{deptno}
 </if>
 </where>
</select>

4、set

EmpMapper.xml配置

<update id="updateEmpBySet" parameterType="Emp">
 update emp
 <set>
 <if test="ename != null and ename != ''">
 ename = #{ename},
 </if>
 <if test="job != null and job != ''">
 job = #{job},
 </if>
 </set> where empno = #{empno}</update>

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表