Mybatis中動態SQL多條件查詢
mybatis中用於實現動態SQL的元素有: if:用if實現條件的選擇,用於定義where的字句的條件。
choose(when otherwise)相當於Java中的switch語句,通常when和otherwise一起使用。
where:簡化SQL語句中的where條件。
set 解決SQL語句中跟新語句
我們課已通過幾個例子來看一下這幾個元素的運用場景:
if:
<select id="queryEmp" resultType="cn.test.entity.Emp"> select * from emp where 1=1 <if test="deptNo!=null"> and deptno=#{deptNO} </if> <if test="deptName!=null"> and deptno=#{deptName} </if> </select> 注:<if test="deptNo!=null">中 的deptNo是指實體類中的屬性或字段;
choose:
<select id="queryEmp" resultType="cn.test.entity.Emp"> select * from emp where 1=1 <choose> <when test="deptNo!=null"> and deptno=#{deptNo} </when> <when test="deptName!=null"> and deptname=#{deptName} </when> <otherwise> and personnum>#{personNum} </otherwise> </choose> </select> 注:上面也說了,choose相當於Java中的switch語句;當第一個when滿足時;就只執行第一個when中的條件。當when中的條件都不滿足時;就會執行默認的的;也就是otherwise中的語句。
where:
<select id="queryEmp" resultType="cn.test.entity.Emp"> select * from emp <where> <if test="deptNo!=null"> and deptno=#{deptNO} </if> <if test="deptName!=null"> and deptno=#{deptName} </if> </where> </select>
注: where下面第一個if語句中以and開頭,也可以省略第一個and ,如果第一個if語句中有and;mybatis會將第一個and忽略。
set:
<update id="updateEmp" parameterType="cn.test.entity.Emp" flushCache="true"> update emp <set> <if test="empName!=null">empname=#{empName},</if> <if test="job!=null">job=#{job}</if> </set> where empno=#{empNo} </update>
注: 在mybatis中的SQL語句結尾不能加“;”,這樣會導致mybatis無法識別字符;導致SQL語句的語法錯誤;出現 java.sql.SQLSyntaxErrorException: ORA-00911: 無效字符的錯誤。的異常。
|