動態語句
-
if動態語句
1.if 按條件是test="" zai在條件中 組裝多個條件要使用英文and or
2.test中直接使用key不需要使用el表達式 sql語句中的參數一定要使用el表達式 -
where語句 針對條件專用
1.where用於動態指定查詢條件,可以沒有條件
2.where一般配合if使用,條件前面一定要加and或者or 關鍵 -
set語句 針對更新語句專用
1.set用於動態更新sql,在更新語句後一定要加,
2.set配合if使用 一般基本類型都不配合if使用 一般都會使用包裝類和null比較 -
sql語句 重複封裝語句
1.引用相同的代碼放到sql標籤中,給他指定ID
2.在需要引用的地方配合 include標籤設置refid爲上面指定的sql的ID
3.where做分頁查詢,查詢的列 -
trim語句(瞭解)
1.prefix 代表最前面需要加上的字符串 prefixOverrides代表最前面需要去掉的字符串
2.suffix 代表最後面需要加上的字符串 suffixOverrides代表最後面需要去掉的字符串 -
foreach 遍歷(實現 in語句)(瞭解)
1.collections 代表需要遍歷的參數 index 代表每次循環的索引 item代表循環的數據體 使用的時候要用el表達式
2.open 以…開頭 close以…結尾 separator分隔符 -
choose 和switch類似(瞭解)
1.choose 配合when和otherwise一起使用
2.當所有的when條件都不滿足的時候會執行otherwise
示例
<sql id="whereCondition">
<where>
<if test="ename!=null and ename!='' ">
and ename like concat('%',#{ename},'%')
</if>
<if test="job!= null and job!='' ">
and job like concat('%',#{job},'%')
</if>
</where>
<!--<trim prefix="where" prefixOverrides="and | or">
<if test="ename!=null and ename!='' ">
and ename like concat('%',#{ename},'%')
</if>
<if test="job!= null and job!='' ">
and job like concat('%',#{job},'%')
</if>
</trim>-->
<!--where 1=1
<choose>
<when test="ename!=null and ename!='' ">
and ename like concat('%',#{ename},'%')
</when>
<when test="job!= null and job!='' ">
and job like concat('%',#{job},'%')
</when>
<otherwise>
<![CDATA[ and hiredate >= #{hiredate} ]]>
</otherwise>
</choose>-->
</sql>
<select id="findEmpByCondition" parameterType="Emp" resultMap="empFKMap">
select * from emp <include refid="whereCondition"></include>
limit #{from},#{rows}
</select>
<select id="findCountByCondition" parameterType="Emp" resultType="int">
select count(0) from emp <include refid="whereCondition"></include>
</select>
<update id="updateEmp" parameterType="Emp">
UPDATE emp
<!--<trim prefix="set" suffixOverrides="," suffix="WHERE EMPNO=#{empno}">
<if test="ename!=null">ENAME=#{ename},</if>
<if test="job!=null">job=#{job},</if>
<if test="hiredate!=null">HIREDATE=#{hiredate},</if>
<if test="password!=null">password=#{password},</if>
</trim>-->
<set>
<if test="ename!=null">ENAME=#{ename},</if>
<if test="job!=null">job=#{job},</if>
<if test="hiredate!=null">HIREDATE=#{hiredate},</if>
<if test="password!=null">password=#{password},</if>
</set>
WHERE EMPNO=#{empno}
</update>
<select id="findEmpByJob" parameterType="list" resultMap="empIDMap">
select * from emp where job in
<foreach collection="jobs" index="index" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
轉義字符
-
在mybatis中不能直接使用 > < …相關的字符 要使用轉義字符
-
CDATA區域可以批量忽視轉義字符 <![CDATA[ ]]>