Mybatis(5)——動態SQL

• if:判斷
• choose (when, otherwise):分支選擇;帶了break的swtich-case
若是帶了id就用id查,若是帶了lastName就用lastName查;只會進入其中一個
• trim 字符串截取(where(封裝查詢條件), set(封裝修改條件))
• foreach 遍歷集合mysql

if進行判斷,其中的test::判斷表達式(OGNL) sql

從參數中取值進行判斷 。碰見特殊符號應該去寫轉義字符:數據庫

<select id="getComplete1">
        SELECT * FROM student WHERE
        <where>
            <if test="id!=null">id=#{id} </if>
            <if test="addr!=null">AND id=#{addr}  </if>
            <if test="stuGender!=null">AND gender=#{stuGender}  </if>
            <if test="name!=null">AND name=#{name}</if>
        </where>
    </select>

trimmybatis

         <trim prefix="WHERE" suffixOverrides="AND">
            <if test="id!=null">id=#{id} AND </if>
            <if test="addr!=null">id=#{addr} AND </if>
            <if test="stuGender!=0">gender=#{stuGender} AND </if>
            <if test="name!=null">name='${name}' AND </if>
</trim>

prefix="":前綴:trim標籤體中是整個字符串拼串 後的結果。 prefix給拼串後的整個字符串加一個前綴
prefixOverrides="": 前綴覆蓋: 去掉整個字符串前面多餘的字符
suffix="":後綴 suffix給拼串後的整個字符串加一個後綴
suffixOverrides="" 後綴覆蓋:去掉整個字符串後面多餘的字符oracle

批量插入ide

 <insert id="insertmanyitem" >
         INSERT INTO student (name,id, gender,addr,c_id) VALUES
         <foreach collection="students" item="stu" separator=",">
             (#{stu.name},#{stu.id},#{stu.stuGender},#{stu.addr},#{stu.college.id})
         </foreach>
    </insert>

    <!--這個就是使用多條查詢-->
    <insert id="insertmanyitem02">
        <foreach collection="students" separator=";" item="stu">
            INSERT INTO student
               <include refid="tableItem"/>
             VALUES
               (#{stu.name},#{stu.id},#{stu.stuGender},#{stu.addr},#{stu.college.id})
        </foreach>
    </insert>

內置參數spa

 兩個內置參數:
         不僅是方法傳遞過來的參數能夠被用來判斷,取值。。。
         mybatis默認還有兩個內置參數:
         _parameter:表明整個參數
             單個參數:_parameter就是這個參數
             多個參數:參數會被封裝爲一個map;_parameter就是表明這個map

         _databaseId:若是配置了databaseIdProvider標籤。
             _databaseId就是表明當前數據庫的別名oracle
    <select id="testInnerPara" resultType="entity.stu">

        <if test="_databaseId=='mysql'">
            SELECT * FROM student
            <if test="_parameter!=null">
                 WHERE id=#{_parameter.id}
            </if>
        </if>
        <if test="_databaseId=='oracle'">
            SELECT * FROM student123 WHERE id=#{_parameter.id}
        </if>
    </select>

抽取可重用的sql片斷。方便後面引用
一、sql抽取:常常將要查詢的列名,或者插入用的列名抽取出來方便引用
二、include來引用已經抽取的sql:
三、include還能夠自定義一些property,sql標籤內部就能使用自定義的屬性
include-property:取值的正確方式${prop},
#{不能使用這種方式}code

<sql id="tableItem">
        (name,id, gender,addr,c_id)
 </sql>
相關文章
相關標籤/搜索