Mybatis全部標簽




一、定義SQL語句

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

(2)insert 標簽的使用
    屬性介紹:
      id :唯一的標識符
      parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User

(3)delete 標簽的使用
    例:

    <delete id="deleteUser" parameterType="int"> 
      delete from user 
      where id = #{id} 
    </delete>

(4)update 標簽的使用
    類似於insert


二、配置對象屬性與查詢結果集

(1)resultMap 標簽的使用

基本作用:建立SQL查詢結果字段與實體屬性的映射關系信息

 查詢的結果集轉換為java對象,方便進一步操作

 將結果集中的列與java對象中的屬性對應起來並將值填充進去

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

例:
<resultMap id="getStudentRM" type="EStudnet"> <id property="id" column="ID"/> <result property="studentName" column="Name"/> <result property="studentAge" column="Age"/> </resultMap>
<select id="getStudent" resultMap="getStudentRM">
  SELECT ID, Name, Age
    FROM TStudent
</select>
標簽說明: 主標簽
id:該resultMap的標志
type:返回值的類名,此例中返回EStudnet類
子標簽:

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



三、動態拼接SQL

(1)if 標簽的使用

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


例:

  1. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from STUDENT_TBL ST       
  3. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  4. </select> 


但是此時如果studentName是null或空字符串,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等於空字符串,我們就不進行此條件的判斷。


修改為:

  1. <select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from STUDENT_TBL ST      
  3.     <if test="studentName!=null and studentName!='' ">     
  4.         WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  5.     </if>     
  6. </select>    



(2)foreach 標簽的使用

foreach標簽主要用於構建in條件,他可以在sql中對集合進行迭代。如下:

  <delete id="deleteBatch"> 

    delete from user where id in

    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">

      #{id}

    </foreach>

  </delete>

  我們假如說參數為----  int[] ids = {1,2,3,4,5}  ----那么打印之后的SQL如下:

  delete form user where id in (1,2,3,4,5)

  釋義:

    collection :collection屬性的值有三個分別是list、array、map三種,分別對應的參數類型為:List、數組、map集合,我在上面傳的參數為數組,所以值為array

    item : 表示在迭代過程中每一個元素的別名

    index :表示在迭代過程中每次迭代到的位置(下標)

    open :前綴

    close :后綴

    separator :分隔符,表示迭代時每個元素之間以什么分隔

我們通常可以將之用到批量刪除、添加等操作中。


(3)choose 標簽的使用

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


         例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。選擇條件順序,when標簽的從上到下的書寫順序:

  1. <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from STUDENT_TBL ST      
  3.     <where>     
  4.         <choose>     
  5.             <when test="studentName!=null and studentName!='' ">     
  6.                     ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.             </when>     
  8.             <when test="studentSex!= null and studentSex!= '' ">     
  9.                     AND ST.STUDENT_SEX = #{studentSex}      
  10.             </when>     
  11.             <when test="studentBirthday!=null">     
  12.                 AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
  13.             </when>     
  14.             <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
  15.                 AND ST.CLASS_ID = #{classEntity.classID}      
  16.             </when>     
  17.             <otherwise>     
  18.                       
  19.             </otherwise>     
  20.         </choose>     
  21.     </where>     
  22. </select>     

四、格式化輸出

(1)where
當if標簽較多時,這樣的組合可能會導致錯誤。例如,like姓名,等於指定性別等:

Xml代碼  

[html]  view plain  copy
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.         WHERE      
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11. </select>     



 如果上面例子,參數studentName為null或’’,則或導致此sql組合成“WHERE AND”之類的關鍵字多余的錯誤SQL。
 這時我們可以使用where動態語句來解決。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND 或OR 開頭的,則它會剔除掉。
 上面例子修改為:

Xml代碼  

[html]  view plain  copy
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </where>     
  12. </select>     


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

Xml代碼  

[html]  view plain  copy
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.        SET STUDENT_TBL.STUDENT_NAME = #{studentName},      
  5.            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  6.            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  7.            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  8.      WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  9. </update>     


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

Xml代碼  

[html]  view plain  copy
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <set>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </set>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     


(3)trim
  trim是更靈活的去處多余關鍵字的標簽,他可以實踐where和set的效果。

 where例子的等效trim語句:


[html]  view plain  copy
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <trim prefix="WHERE" prefixOverrides="AND|OR">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </trim>     
  12. </select>     


set例子的等效trim語句:

Xml代碼  

[html]  view plain  copy
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <trim prefix="SET" suffixOverrides=",">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </trim>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     

五、配置關聯關系

(1)collection

一對一

association通常用來映射一對一的關系,例如,有個類user,對應的實體類如下:(getter,setter方法省略)

    private String id;//主鍵
    private String userName;//用戶姓名

 

有個類Article,對應的實體類如下:

    private String id;//主鍵
    private String articleTitle;//文章標題
    private String articleContent;//文章內容
  

如果我想查詢一個用戶的時候,也查到他寫的一篇文章,可以怎樣寫呢?在類user加入一個屬性article

   private String id;//主鍵
   private String userName;//用戶姓名
   private Article article;//新增的文章屬性
 

2、mapper.xml 我在user類的mapper.xml這樣配置

    

復制代碼
<resultMap id="userResultMap" type="test.mybatis.entity.User">
  <id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
  <result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>
//這里把user的id傳過去
   <association property="article" column="id" select="test.mybatis.dao.articleMapper.selectArticleByUserId" />//test.mybatis.dao.articleMapper為命名空間
 </resultMap>
復制代碼

同時,我的article對應的xml這樣寫:

復制代碼
1 <resultMap id="articleResultMap" type="test.mybatis.entity.Article">
2   <id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
3   <result column="articleTitle" property="articleTitle" jdbcType="VARCHAR" javaType="java.lang.String"/>
4  <result column="articleContent" property="articleContent" jdbcType="VARCHAR" javaType="java.lang.String"/>
5  </resultMap>
  (當然,這里還有查詢user表的語句,省略)

 

復制代碼

同時,在article對應的xml有這樣的select語句:

<select id="selectArticleByUserId"
parameterType="java.lang.String"
resultMap="ArticleResultMap" >
select * from
tb_article where userId=#{userId} </select>

(2)association

一對多

實體類增加對應屬性

  private String id;//主鍵
   private String userName;//用戶姓名
   private List<Article> articleList;

userMapper.xml這樣配置

復制代碼
<resultMap id="userResultMap" type="test.mybatis.entity.User">
  <id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
  <result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>
//這里把user的id傳過去
   <collection property="articleList" column="id"                       
            select="test.mybatis.dao.articleMapper.selectArticleListByUserId" />
 </resultMap>
以下省略,類同,Mybatis會把結果封裝成List類型。
復制代碼

三、如果我還想通過Article表另一張表,比如文章中有個fk_id,也可以像上面這樣重復配置,把fk_id當做與另一張表關聯的參數,那時就可以通過用戶查到文章,查到文章關聯的另一張表了。


六、SQL標簽

更多用於寫sql語句的一部分,寫在配置文件中的常量


七、include標簽

用於引用常量


免責聲明!

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



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