Mybatis動態sql無註解的簡單寫法
阿新 • • 發佈:2018-12-21
動態 SQL 元素和使用 JSTL 或其他類似基於 XML 的文字處理器相似。在 MyBatis 之前的版本中,有很多的元素需要來了解。MyBatis 3 大大提升了它們,現在用不到原先一半的元素就可以了。MyBatis 採用功能強大的基於 OGNL 的表示式來消除其他元素。 if choose (when, otherwise) trim (where, set) foreach
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 對映檔案規範: namespace屬性不能少 sql語句 >>查詢 必須告知單行返回的型別 --> <mapper namespace="com.pk.sql.EmpMapper"> <resultMap type="com.pk.sql.Emp" id="empType"> </resultMap> <!-- <where>標籤 1.會自動給你加一個where 2.然後會刪除第一個遇見的and(如果and前面有其他字母則不會刪除and) --> <select id="queryEmp" parameterType="emps" resultMap="empType"> select * from emp <where> <if test="ename!=null"> and ename LIKE #{ename} </if> <!-- int是不等於0 多條件 --> <if test="sal==0 and ename==null"> and sal = #{sal} </if> </where> </select> <!-- <choose>標籤 1.相當於java裡面的switch語句 2.只能滿足一個條件 --> <select id="queryEmp1" parameterType="emps" resultMap="empType"> select * from emp <where> <choose> <when test="sal!=0 and ename==null"> and sal = #{sal} </when> <when test="ename!=null"> and ename LIKE #{ename} </when> <otherwise> 1=1 LIMIT 0,2 </otherwise> </choose> </where> </select> <!-- <trim>標籤: 1.prefix屬性:指前面一定會加上你指定的值 2.prefixOverrides屬性:往下找如果第一個找到的值是你指定的值那麼將prefix的值替換成你找到的值的位置 --> <select id="queryEmp2" parameterType="emps" resultMap="empType"> select * from emp <trim prefixOverrides="and" prefix="where"> <choose> <when test="sal!=0 and ename==null"> and sal = #{sal} </when> <when test="ename!=null"> and ename LIKE #{ename} </when> <otherwise> 1=1 LIMIT 0,2 </otherwise> </choose> </trim> </select> <!-- <set>標籤 >>>>>>>> 一般用作修改 1.自動增加一個set 2.去除<set>標籤中最後一個, --> <update id="updateEmp" parameterType="emps"> update emp <!-- <trim suffixOverrides="," suffix="" prefix="set"> --> <set> <if test="ename!=null"> ename=#{ename}, </if> <if test="sal!=0"> sal = #{sal}, </if> </set> <!-- </trim> --> where empno = #{empno} </update> <!-- <foreach>標籤 1.collection屬性:從引數類中拿出資料來源進行迴圈 2.item屬性:表示每次迴圈出的結果 3.open屬性:在迴圈開始之前打出指定的值 4,close屬性:在迴圈開始之後打出指定的值 5.separator屬性:將每個結果值以指定的值連起來 --> <select id="queryEmp3" parameterType="emps" resultType="emps"> SELECT * FROM emp where deptNo in <foreach item="deptNo" open="(" close=")" collection="deptNoList" separator=","> #{deptNo} </foreach> </select> </mapper>