ssm框架之持久層mybatis動態sql標簽屬性大全


參考並轉自:https://www.cnblogs.com/zjfjava/p/8886432.html

 

1. 定義sql語句

1.1 select 標簽

  • id :唯一的標識符.
  • parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User或user
  • resultType :語句返回值類型或別名。注意,如果是集合,那么這里填寫的是集合的泛型,而不是集合本身(resultType 與resultMap 不能並用)
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
            select * from student where id=#{id}
    </select>

    1.2 insert標簽

    屬性介紹:

  • id :唯一的標識符
  • parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User
    <insert id="insert" parameterType="Object">
            insert into student    <trim     prefix="("    suffix=")"    suffixOverrides="," >    
        <if test="name != null  "> NAME,  </if>    
        </trim>    <trim     prefix="values("    suffix=")"    suffixOverrides="," >
        <if test="name != null  ">  #{name},  </if>    
        </trim>
    </insert>

    1.3 delete標簽

    屬性同 insert

    <delete id="deleteByPrimaryKey" parameterType="Object">
            delete      from student where id=#{id}
    </delete>

    1.4 update標簽

    屬性同 insert

2. 配置JAVA對象屬性與查詢結果集中列名對應關系

resultMap 標簽的使用
基本作用:

  • 建立SQL查詢結果字段與實體屬性的映射關系信息
  • 查詢的結果集轉換為java對象,方便進一步操作。
  • 將結果集中的列與java對象中的屬性對應起來並將值填充進去

!注意:與java對象對應的列不是數據庫中表的列名,而是查詢后結果集的列名

<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
        <id property="id" column="id" />
        <result column="NAME" property="name" />
        <result column="HOBBY" property="hobby" />
        <result column="MAJOR" property="major" />
        <result column="BIRTHDAY" property="birthday" />
        <result column="AGE" property="age" />

</resultMap>
  <!--查詢時resultMap引用該resultMap -->  
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
        select id,name,hobby,major,birthday,age from student where id=#{id}
</select>

標簽說明:

主標簽:

  • id:該resultMap的標志
  • type:返回值的類名,此例中返回Studnet類

子標簽:

  • id:用於設置主鍵字段與領域模型屬性的映射關系,此處主鍵為ID,對應id。
  • result:用於設置普通字段與領域模型屬性的映射關系

3. 動態sql拼接

3.1 if 標簽

if標簽通常用於WHERE語句、UPDATE語句、INSERT語句中,通過判斷參數值來決定是否使用某個查詢條件、判斷是否更新某一個字段、判斷是否插入某個字段的值。

<if test="name != null and name != ''">
         and NAME = #{name}
</if>

3.2 foreach 標簽

foreach標簽主要用於構建in條件,可在sql中對集合進行迭代。也常用到批量刪除、添加等操作中。

<!-- in查詢所有,不分頁 -->
    <select id="selectIn" resultMap="BaseResultMap">
        select name,hobby 
              from student where id in
        <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

屬性介紹:

  • collection:collection屬性的值有三個分別是list、array、map三種,分別對應的參數類型為:List、數組、map集合。
  • item :表示在迭代過程中每一個元素的別名
  • index :表示在迭代過程中每次迭代到的位置(下標)
  • open :前綴
  • close :后綴
  • separator :分隔符,表示迭代時每個元素之間以什么分隔

3.3 choose標簽

  有時候我們並不想應用所有的條件,而只是想從多個選項中選擇一個。MyBatis提供了choose 元素,按順序判斷when中的條件出否成立,如果有一個成立,則choose結束。當choose中所有when的條件都不滿則時,則執行 otherwise中的sql。類似於Java 的switch 語句,choose為switch,when為case,otherwise則為default。

 if是與(and)的關系,而choose是或(or)的關系。

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">     
    SELECT * from STUDENT WHERE 1=1    
    <where>     
        <choose>     
            <when test="Name!=null and student!='' ">     
                   AND name LIKE CONCAT(CONCAT('%', #{student}),'%')      
            </when>     
            <when test="hobby!= null and hobby!= '' ">     
                    AND hobby = #{hobby}      
            </when>                   
            <otherwise>     
                    AND AGE = 15  
            </otherwise>     
        </choose>     
    </where>     
</select>

4. 格式化輸出

4.1 where標簽

當if標簽較多時,這樣的組合可能會導致錯誤。 如下:

<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from STUDENT      
        WHERE      
        <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{name}),'%')      
        </if>     
        <if test="hobby!= null and hobby!= '' ">     
            AND hobby = #{hobby}      
        </if>     
</select>

當name值為null時,查詢語句會出現 “WHERE AND” 的情況,解決該情況除了將"WHERE"改為“WHERE 1=1”之外,還可以利用where標簽。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND 或OR 開頭的,則它會剔除掉。

<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from STUDENT      
       <where>   
         <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{name}),'%')      
         </if>     
         <if test="hobby!= null and hobby!= '' ">     
            AND hobby = #{hobby}      
         </if>  
       </where>        
</select>

4.2 set 標簽

沒有使用if標簽時,如果有一個參數為null,都會導致錯誤。當在update語句中使用if標簽時,如果最后的if沒有執行,則或導致逗號多余錯誤。使用set標簽可以將動態的配置set關鍵字,和剔除追加到條件末尾的任何不相關的逗號。

<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT   
       SET NAME = #{name},   
           MAJOR = #{major},
           HOBBY = #{hobby}
     WHERE ID = #{id};      
</update>
<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT SET    
        <if test="name!=null and name!='' ">     
            NAME = #{name},      
        </if>     
        <if test="hobby!=null and hobby!='' ">     
            MAJOR = #{major},      
        </if> 
        <if test="hobby!=null and hobby!='' ">     
            HOBBY = #{hobby}    
        </if>          
    WHERE ID = #{id};      
</update>

使用set+if標簽修改后,如果某項為null則不進行更新,而是保持數據庫原值。

<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT      
    <set>     
        <if test="name!=null and name!='' ">     
            NAME = #{name},      
        </if>     
        <if test="hobby!=null and hobby!='' ">     
            MAJOR = #{major},      
        </if> 
        <if test="hobby!=null and hobby!='' ">     
            HOBBY = #{hobby}    
        </if>     
    </set>     
    WHERE ID = #{id};      
</update>

4.3 trim標簽

格式化輸出,也可以通過trim標簽設定或忽略前后綴來實現,詳見大佬博客

5. 配置關聯關系

5.1 collection標簽

5.2 association標簽

關於關聯映射關系,詳細參考這篇博客

6. 定義常量及引用

6.1 sql標簽

當多種類型的查詢語句的查詢字段或者查詢條件相同時,可以將其定義為常量,方便調用。為求<select>結構清晰也可將sql語句分解。

<!-- 查詢字段 -->
    <sql id="Base_Column_List">
        ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
    </sql>

 <!-- 查詢條件 -->
    <sql id="Example_Where_Clause">
        where 1=1
        <trim suffixOverrides=","> 
            <if test="id != null and id !=''">
                and id = #{id}
            </if>
            <if test="major != null and major != ''">
                and MAJOR = #{major}
            </if>
            <if test="birthday != null ">
                and BIRTHDAY = #{birthday}
            </if>
            <if test="age != null ">
                and AGE = #{age}
            </if>
            <if test="name != null and name != ''">
                and NAME = #{name}
            </if>
            <if test="hobby != null and hobby != ''">
                and HOBBY = #{hobby}
            </if>            
            <if test="sorting != null">
                order by #{sorting}
            </if>
            <if test="sort!= null  and sort != '' ">
                order by ${sort}   ${order}
            </if>

        </trim>
    </sql>

6.2 include標簽

用於引用定義的常量

<!-- 查詢所有,不分頁 -->
    <select id="selectAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM
        student
        <include refid="Example_Where_Clause" />
    </select>
    
<!-- 分頁查詢 -->
    <select id="select" resultMap="BaseResultMap">
    
    
        select * from (
            select tt.*,rownum as rowno from 
                (
                    SELECT
                    <include refid="Base_Column_List" /> 
                    FROM
                    student
                    <include refid="Example_Where_Clause" />
                     ) tt 
                     <where>
                            <if test="pageNum != null and rows != null">
                            and  rownum  <![CDATA[<=]]>#{page}*#{rows}
                         </if>
                    </where>
             ) table_alias
            where table_alias.rowno>#{pageNum}
              
              
    </select>
<!-- 根據條件刪除 -->
    <delete id="deleteByEntity" parameterType="java.util.Map">
    DELETE  FROM   student
    <include refid="Example_Where_Clause" />
    </delete>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM