1. 程式人生 > 程式設計 >Mybatis中Mapper標籤總結大全

Mybatis中Mapper標籤總結大全

一、標籤分類

定義SQL語句

  • insert
  • delete
  • update
  • select

配置關聯關係

  • collection
  • association

配置java物件屬性與查詢結果集中列名的對應關係

  • resultMap

控制動態SQL拼接

  • foreach
  • if
  • choose

格式化輸出

  • where
  • set
  • trim

定義常量

  • sql

其他

  • include

二、標籤總結

1. 基礎SQL標籤

1.1 查詢select

標籤屬性

  • id 唯一的名稱,對應dao中mapper的介面名稱
  • paramterType 定義傳入的引數型別
  • resultType 返回資料型別對應實體類
  • resultMap 外部 resultMap 的命名引用。結果集的對映是 MyBatis 最強大的特性,對其有一個很好的理解的話,許多複雜對映的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同時使用
  • flushCache 將其設定為 true,任何時候只要語句被呼叫,都會導致本地快取和二級快取都會被清空,預設值:false
  • useCache 將其設定為 true,將會導致本條語句的結果被二級快取,預設值:對 select 元素為 true
  • timeout 這個設定是在丟擲異常之前,驅動程式等待資料庫返回請求結果的秒數。預設值為 unset(依賴驅動)
  • fetchSize 這是嘗試影響驅動程式每次批量返回的結果行數和這個設定值相等。預設值為 unset(依賴驅動)。
  • statementType STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,預設值:PREPARED。
  • resultSetType FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個,預設值為 unset (依賴驅動)。
  • databaseId 如果配置了 databaseIdProvider,MyBatis 會載入所有的不帶 databaseId 或匹配當前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。
  • resultOrdered 這個設定僅針對巢狀結果 select 語句適用:如果為true,就是假設包含了巢狀結果集或是分組了,這樣的話當返回一個主結果行的時候,就不會發生有對前面結果集的引用的情況。這就使得在獲取巢狀的結果集的時候不至導致記憶體不夠用。預設值:false。
  • resultSets 這個設定僅對多結果集的情況適用,它將列出語句執行後返回的結果集並每個結果集給一個名稱,名稱是逗號分隔的。
  /**
   * 根據條件查詢使用者集合
   */
  List<User> selectUsers(@Param("cond")Map<String,Object> map);
<!-- 返回的是List,resultType給定的值是List裡面的實體類而不是list,mybatis會自動把結果變成List -->
  <select id="selectUsers" parameterType="map" resultType="con.it.bean.User">
    select id,username,password,sex,birthday,address from user u
    <where>
      <trim suffixOverrides=",">
        <if test="cond.username != null and cond.username != ''">
          u.username = #{cond.username},</if>
        <if test="cond.sex != null">
          and u.sex = #{cond.sex},</if>
         <if test="cond.beginTime != null">
          <![CDATA[ and DATE_FORMAT(u.birthday,'%Y-%m-%d %H:%T:%s') >= DATE_FORMAT(#{beginTime},'%Y-%m-%d %H:%T:%s'),  ]]>
        </if>
        <if test="cond.endTime != null">
          <![CDATA[ and DATE_FORMAT(u.birthday,'%Y-%m-%d %H:%T:%s') <= DATE_FORMAT(#{endTime},'%Y-%m-%d %H:%T:%s'),  ]]>
        </if>
        <if test="cond.address != null and cond.address != ''">
          and u.addrerss like '%' || #{cond.address} || '%',</if>
      </trim>
    </where>
  </select>

1.2 增刪改

標籤屬性

  • id 唯一的名稱,對應dao中mapper的介面名稱
  • parameterType 將要傳入語句的引數的完全限定類名或別名。這個屬性是可選的,因為 MyBatis 可以通過 TypeHandler 推斷出具體傳入語句的引數,預設值為 unset。
  • flushCache 將其設定為 true,任何時候只要語句被呼叫,都會導致本地快取和二級快取都會被清空,預設值:true(對應插入、更新和刪除語句)。
  • timeout 這個設定是在丟擲異常之前,驅動程式等待資料庫返回請求結果的秒數。預設值為 unset(依賴驅動)。
  • statementType STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,預設值:PREPARED。
  • useGeneratedKeys(僅對 insert 和 update 有用)這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由資料庫內部生成的主鍵(比如:像 MySQL 和 SQL Server這樣的關係資料庫管理系統的自動遞增欄位,oracle使用序列是不支援的,通過selectKey可以返回主鍵),預設值:false。
  • keyProperty (僅對 insert 和 update 有用)唯一標記一個屬性,MyBatis 會通過 getGeneratedKeys 的返回值或者通過 insert 語句的 selectKey子元素設定它的鍵值,預設:unset。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。
  • keyColumn(僅對 insert 和 update 有用)通過生成的鍵值設定表中的列名,這個設定僅在某些資料庫(像PostgreSQL)是必須的,當主鍵列不是表中的第一列的時候需要設定。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。
  • databaseId 如果配置了 databaseIdProvider,MyBatis 會載入所有的不帶 databaseId 或匹配當前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。
  <insert id="insert" parameterType="com.it.bean.User">
  
    <!-- 使用序列插入oracle資料庫返回主鍵,MYSQL資料庫無需新增selectKey -->
    <selectKey resultType="long" order="BEFORE" keyProperty="id">
      SELECT user_seq.NEXTVAL as id from DUAL
    </selectKey>
    
    insert into User (ID,USERNAME,PASSWORD,SEX,ADRESS,CREATED_BY,CREADTED_DATE)
    values (#{id},#{username},#{password},#{sex},#{adress},#{createdBy},SYSDATE)
  </insert>

1.3 其他基礎標籤

1.3.1 sql 標籤

定義一些常用的sql語句片段

<sql id="selectParam">
  id,address
</sql>

1.3.2 include 標籤

引用其他的常量,通常和sql一起使用

<select>
  select <include refid="selectParam"></include>
  from user
</select>

1.3.3 if 標籤

基本都是用來判斷值是否為空,注意Integer的判斷,mybatis會預設把0變成 ‘'

<if test="item != null and item != ''"></if>

<!-- 如果是Integer型別的需要把and後面去掉或是加上or-->
<if test="item != null"></if>
<if test="item != null and item != '' or item == 0"></if>

1.3.4 別名

經常使用的型別可以定義別名,方便使用,mybatis也註冊了很多別名方便我們使用,詳情見底部附錄

<typeAliases>
   <typeAlias type="com.it.bean.User" alias="User"/>
</typeAliases>

2. collection與association標籤

collection與association的屬性一樣,都是用於resultMap返回關聯對映使用,collection關聯的是集合,而association是關聯單個物件

標籤屬性

  • property resultMap返回實體類中欄位和result標籤中的property一樣
  • column 資料庫的列名或者列標籤別名,是關聯查詢往下一個語句傳送值。注意: 在處理組合鍵時,您可以使用column=“{prop1=col1,prop2=col2}”這樣的語法,設定多個列名傳入到巢狀查詢語句。這就會把prop1和prop2設定到目標巢狀選擇語句的引數物件中。
  • javaType 一般為ArrayList或是java.util.List
  • ofType java的實體類,對應資料庫表的列名稱,即關聯查詢select對應返回的類
  • select 執行一個其他對映的sql語句返回一個java實體型別
/**
 *問題表
 */
public class Question {
  
  private Long id; //問題id

  private String question; //問題
  
  private Integer questionType; //問題型別
  
  private List<QuestionAnswer> answerList; //問題選項集合
  
  //Getter和Setter省略
}

/**
 *問題選項表
 */
public class QuestionAnswer {
  
  private Long id; //選項id
  
  private Long questionId; //問題id

  private String answer; //選項
  
  //Getter和Setter省略
}

<!-- 具體可參考下面ResultMap -->
<collection property="answerList" javaType="java.util.List"
        ofType="com.it.bean.QuestionAnswer" column="id" 
        select="setlectQuestionAnswerByQuestionId"/>

3. resultMap標籤

resultMap屬性

  • id 唯一標識
  • type 返回型別
  • extends 繼承別的resultMap,可選

關聯其他標籤

  • id 設定主鍵使用,使用此標籤配置對映關係(可能不止一個)
  • result 一般屬性的配置對映關係,一般不止一個
  • association 關聯一個物件使用
  • collection 關聯一個集合使用
<!-- 返回關聯查詢的問題 -->
<resultMap id="detail_result" type="com.it.bean.Question">
  <id column="id" property="id" />
  <result column="question" property="question" />
  <result column="question_type" property="questionType" />
  <collection property="answerList" javaType="java.util.List"
        ofType="com.it.bean.QuestionAnswer" column="id" 
        select="setlectQuestionAnswerByQuestionId"/>
</resultMap>

<!-- 查詢問題集 -->
<select id="selectQuestions" parameterType="map" resultMap="detail_result">
  select q.id,q.question,q.question_type 
  from question q 
  <where>
    <if test="cond.id != null">
      q.id = #{cond.id}
    </if>
    <if test="cond.idList != null and cond.idList.size() != 0">
      q.id in 
      <foreach collection="cond.idList" item="id" open="(" separator="," close=")">
        #{id}
      </foreach>
    </if>
  </where>
</select>

<!-- 查詢對應問題的答案集 -->
<select id="setlectQuestionAnswerByQuestionId" parameterType="long" resultType="com.it.bean.QuestionAnswer">
  select a.id,a.answer from question_answer a where a.question_id = #{id}
</select>

4. foreach標籤

foreach屬性

  • collection 迴圈的集合。傳的是集合為list,陣列為array,如果是map為java.util.HashMap
  • item 迴圈的key
  • index 迴圈的下表順序
  • open 迴圈的開頭
  • close 迴圈結束
  • separator 迴圈的分隔符
<sql id="base_column">id,question_id,answer</sql>

<!-- oracle的批量插入 -->
<insert id="insertBatchOracle" parameterType="list">
  insert into question_answer ( <include refid="base_column" /> ) 
  select question_answer_seq.NEXTVAL,A.* from (
    <foreach collection="list" item="item" separator="union all">
      select #{item.questionId},#{item.answer} from dual
    </foreach>
  ) A 
</insert>

<!-- Mysql的批量插入,主鍵自增 -->
<insert id="insertBatchMysql" parameterType="list">
  insert into question_answer ( <include refid="base_column" /> ) 
  values 
    <foreach collection="list" item="item" open="(" separator="union all" close=")">
      #{item.id},#{item.questionId},#{item.answer}
    </foreach>
</insert>

5. where標籤

where用來去掉多條件查詢時,開頭多餘的and

  <select id="selectUserList" parameterType="com.it.bean.User" resultType="com.it.bean.User">
    <!-- 引用Sql片段 -->
    select <include refid="selectParam"> from user u
    <where>
      <!--where 可以自動去掉條件中的第一個and-->
      <if test="id != null">
        and u.id = #{id}
      </if>
      <if test="name != null and name != ''">
        and u.name = #{name}
      </if>
    </where>
  </select>

6. set標籤

set是mybatis提供的一個智慧標記,當在update語句中使用if標籤時,如果前面的if沒有執行,則或導致逗號多餘錯誤。使用set標籤可以將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。
沒有使用if標籤時,如果有一個引數為null,都會導致錯誤,如下示例:

  <update id="updateUser" parameterType="com.it.bean.user">
    update user
    <set>
      <if test="username != null and username != ''">
        username = #{username},</if>
      <if test="sex != null and sex == 0 or sex == 1">
        sex = #{sex},</if>
      <if test="birthday != null "> 
        birthday = #{birthday},</if > 
      <if test="address != null and address != ''">
        address = #{address},</if>
      <if test="lastModifiedBy != null and lastModifiedBy != ''">
        last_modified_by = #{lastModifiedBy},last_modified_date = SYSDATE,</if>
    </set>
    <where>
      id = #{id}
    </where>
  </update>

7. trim標籤

trim標記是一個格式化的標記,可以完成set或者是where標記的功能

標籤屬性

  • prefix、suffix 表示再trim標籤包裹部分的前面或後面新增內容(注意:是沒有prefixOverrides,suffixOverrides的情況下)
  • prefixOverrides,suffixOverrides 表示覆蓋內容,如果只有這兩個屬性表示刪除內容
<update id="test" parameterType="com.it.bean.User">
  update user
    <!-- 開頭加上set,結尾去除最後一個逗號 -->
    <trim prefix="set" suffixOverrides=",">
      <if test="username!=null and username != ''">
        name= #{username},</if>

      <if test="password!=null and password != ''">
        password= #{password},</if>

    </trim>
    <where>
      id = #{id}
    </where>
  </update>

8. choose、when、otherwise標籤

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

<select id="getUserList" resultType="com.it.bean.User" parameterType="com.it.bean.User"> 
  SELECT <include refid="resultParam"></include> FROM User u  
  <where> 
    <choose> 
      <when test="username !=null and username != ''"> 
        u.username LIKE CONCAT(CONCAT('%',#{username}),'%') 
      </when > 
      <when test="sex != null"> 
        AND u.sex = #{sex} 
      </when > 
      <when test="birthday != null "> 
        AND u.birthday = #{birthday} 
      </when > 
      <otherwise> 
      </otherwise> 
    </choose> 
  </where>  
</select> 

附Mybatis已經註冊好的別名表

別名 對映型別
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
map Map
hashmap HashMap
list list
arraylist ArrayList
collection Collection
iterator Iterator

二、寫在後面

在網上看了很多標籤的解釋,但不是很全,我就自己總結了一份,搭配示例更好理解標籤的含義,如有什麼遺漏或是錯誤還望多多發言補充,我會繼續完善。

注: 關於引數指定jdbcType,是因為當傳參為null時候,mybatis無法自動判斷型別,就必須要顯示指定它的型別,多用於insert中

到此這篇關於Mybatis中Mapper標籤總結大全的文章就介紹到這了,更多相關Mybatis Mapper標籤內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!