1. 程式人生 > 程式設計 >Mybatis中Mapper對映檔案使用詳解

Mybatis中Mapper對映檔案使用詳解

緊接上文所述,在這篇文章中我將對Mapper對映檔案進行詳細的說明。

Mapper對映檔案是一個xml格式檔案,必須遵循相應的dtd檔案規範,如ibatis-3-mapper.dtd。我們先大體上看看支援哪些配置?如下所示,從Eclipse裡截了個屏:

Mybatis中Mapper對映檔案使用詳解

從上圖可以看出,對映檔案是以<mapper>作為根節點,在根節點中支援9個元素,分別為insert、update、delete、select(增刪改查);cache、cache-ref、resultMap、parameterMap、sql。

下文中,我們將首先對增刪改進行描述,然後對查進行詳細說明,最後對其他五個元素進行簡單說明。

(1)insert、update、delete

我們先從配置檔案看起:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" 
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 

<!-- mapper 為根元素節點, 一個namespace對應一個dao -->
<mapper namespace="com.dy.dao.UserDao">

  <insert
   <!-- 1. id (必須配置)
    id是名稱空間中的唯一識別符號,可被用來代表這條語句。 
    一個名稱空間(namespace) 對應一個dao介面,這個id也應該對應dao裡面的某個方法(相當於方法的實現),因此id 應該與方法名一致 -->
   
   id="addUser"
   
   <!-- 2. parameterType (可選配置,預設為mybatis自動選擇處理)
    將要傳入語句的引數的完全限定類名或別名, 如果不配置,mybatis會通過ParameterHandler 根據引數型別預設選擇合適的typeHandler進行處理
    parameterType 主要指定引數型別,可以是int,short,long,string等型別,也可以是複雜型別(如物件) -->
   
   parameterType="user"
   
   <!-- 3. flushCache (可選配置,預設配置為true)
    將其設定為 true,任何時候只要語句被呼叫,都會導致本地快取和二級快取都會被清空,預設值:true(對應插入、更新和刪除語句) -->
   
   flushCache="true"
   
   <!-- 4. statementType (可選配置,預設配置為PREPARED)
    STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,預設值:PREPARED。 -->
   
   statementType="PREPARED"
   
   <!-- 5. keyProperty (可選配置, 預設為unset)
    (僅對 insert 和 update 有用)唯一標記一個屬性,MyBatis 會通過 getGeneratedKeys 的返回值或者通過 insert 語句的 selectKey 子元素設定它的鍵值,預設:unset。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。 -->
   
   keyProperty=""
   
   <!-- 6. keyColumn   (可選配置)
    (僅對 insert 和 update 有用)通過生成的鍵值設定表中的列名,這個設定僅在某些資料庫(像 PostgreSQL)是必須的,當主鍵列不是表中的第一列的時候需要設定。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。 -->
   
   keyColumn=""
   
   <!-- 7. useGeneratedKeys (可選配置, 預設為false)
    (僅對 insert 和 update 有用)這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由資料庫內部生成的主鍵(比如:像 MySQL 和 SQL Server 這樣的關係資料庫管理系統的自動遞增欄位),預設值:false。 -->
   
   useGeneratedKeys="false"
   
   <!-- 8. timeout (可選配置, 預設為unset,依賴驅動)
    這個設定是在丟擲異常之前,驅動程式等待資料庫返回請求結果的秒數。預設值為 unset(依賴驅動)。 -->
   timeout="20">

  <update
   id="updateUser"
   parameterType="user"
   flushCache="true"
   statementType="PREPARED"
   timeout="20">

  <delete
   id="deleteUser"
   parameterType="user"
   flushCache="true"
   statementType="PREPARED"
   timeout="20">
</mapper>

上面給出了一個比較全面的配置說明,但是在實際使用過程中並不需要都進行配置,可根據自己的需要刪除部分配置項。

在這裡,我列舉出我自己的配置檔案,精簡之後是這樣的:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" 
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.majing.learning.mybatis.dao.UserDao">
	
	<insert id="addUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
		insert into user(name,password,age) values(#{name},#{password},#{age})
	</insert>
	
	<delete id="deleteUser" parameterType="int">
		delete from user where id = #{id}
	</delete>
	
	<update id="updateUser" parameterType="user" >
		update user set name = #{name},password = #{password},age = #{age} where id = #{id}
	</update>
	
	
 
</mapper>

這裡的parameterType設定成user是因為如果不設定的情況下,會自動將類名首字母小寫後的名稱,原來的類名為User。不過,建議大家還是使用typeAlias進行配置吧。唯一需要說明的就是<insert>元素裡面的useGeneratedKeys和keyProperties屬性,這兩個屬性是用來獲取資料庫中的主鍵的。

在資料庫裡面經常性的會給資料庫表設定一個自增長的列作為主鍵,如果我們操作資料庫後希望能夠獲取這個主鍵該怎麼弄呢?正如上面所述,如果是支援自增長的資料庫,如mysql資料庫,那麼只需要設定useGeneratedKeys和keyProperties屬性便可以了,但是對於不支援自增長的資料庫(如oracle)該怎麼辦呢?

mybatis裡面在<insert>元素下面提供了<selectKey>子元素用於幫助解決這個問題。來看下配置:

<selectKey
    <!-- selectKey 語句結果應該被設定的目標屬性。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。 -->
    keyProperty="id"
    <!-- 結果的型別。MyBatis 通常可以推算出來,但是為了更加確定寫上也不會有什麼問題。MyBatis 允許任何簡單型別用作主鍵的型別,包括字串。如果希望作用於多個生成的列,則可以使用一個包含期望屬性的 Object 或一個 Map。 -->
    resultType="int"
    <!-- 這可以被設定為 BEFORE 或 AFTER。如果設定為 BEFORE,那麼它會首先選擇主鍵,設定 keyProperty 然後執行插入語句。如果設定為 AFTER,那麼先執行插入語句,然後是 selectKey 元素 - 這和像 Oracle 的資料庫相似,在插入語句內部可能有嵌入索引呼叫。 -->
    order="BEFORE"
    <!-- 與前面相同,MyBatis 支援 STATEMENT,PREPARED 和 CALLABLE 語句的對映型別,分別代表 PreparedStatement 和 CallableStatement 型別。 -->
    statementType="PREPARED">
</selectKey>

針對不能使用自增長特性的資料庫,可以使用下面的配置來實現相同的功能:

<insert id="insertUser" parameterType="com.dy.entity.User">
      <!-- oracle等不支援id自增長的,可根據其id生成策略,先獲取id -->
      
    <selectKey resultType="int" order="BEFORE" keyProperty="id">
       select seq_user_id.nextval as id from dual
    </selectKey>
 
      insert into user(id,name,age,deleteFlag) 
        values(#{id},#{name},#{age},#{deleteFlag})
  </insert>

講完了insert、update、delete,接下來我們看看用的比較多的select。

(2)select、resultType、resultMap

我們先來看看select元素都有哪些配置可以設定:

<select
    <!-- 1. id (必須配置)
    id是名稱空間中的唯一識別符號,可被用來代表這條語句。 
    一個名稱空間(namespace) 對應一個dao介面,這個id也應該對應dao裡面的某個方法(相當於方法的實現),因此id 應該與方法名一致 -->
   
   id="findUserById"
   
   <!-- 2. parameterType (可選配置,string等型別,也可以是複雜型別(如物件) -->
   parameterType="int"
   
   <!-- 3. resultType (resultType 與 resultMap 二選一配置)
     resultType用以指定返回型別,指定的型別可以是基本型別,可以是java容器,也可以是javabean -->
   resultType="User"
   
   <!-- 4. resultMap (resultType 與 resultMap 二選一配置)
     resultMap用於引用我們通過 resultMap標籤定義的對映型別,這也是mybatis元件高階複雜對映的關鍵 -->
   resultMap="userResultMap"
   
   <!-- 5. flushCache (可選配置)
     將其設定為 true,任何時候只要語句被呼叫,都會導致本地快取和二級快取都會被清空,預設值:false -->
   flushCache="false"
   
   <!-- 6. useCache (可選配置)
     將其設定為 true,將會導致本條語句的結果被二級快取,預設值:對 select 元素為 true -->
   useCache="true"
   
   <!-- 7. timeout (可選配置) 
     這個設定是在丟擲異常之前,驅動程式等待資料庫返回請求結果的秒數。預設值為 unset(依賴驅動)-->
   timeout="10000"
   
   <!-- 8. fetchSize (可選配置) 
     這是嘗試影響驅動程式每次批量返回的結果行數和這個設定值相等。預設值為 unset(依賴驅動)-->
   fetchSize="256"
   
   <!-- 9. statementType (可選配置) 
     STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,預設值:PREPARED-->
   statementType="PREPARED"
   
   <!-- 10. resultSetType (可選配置) 
     FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個,預設值為 unset (依賴驅動)-->
   resultSetType="FORWARD_ONLY">

我們還是從具體的示例來看看,

<select id="findUserById" resultType="User">
	select * from user where id = #{id}
</select>

這裡我們根據使用者id去查詢這個使用者的資訊,resultType=User是一個別名,如果我們接觸到的是這種一對一的問題,那麼可以簡單的定義一個實體,這個實體代表資料庫表中的一條記錄即可。但是如果我們遇到一對多的問題呢,就拿這裡的查詢使用者資訊來說,如果每個使用者有各種興趣,需要維護每個使用者的興趣資訊,那麼我們可能就存在下面的資料表結構:

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,`password` varchar(255) NOT NULL,`age` int(3) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
 
CREATE TABLE `userinterests` (
 `userid` int(11) DEFAULT NULL,`interestid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
CREATE TABLE `interests` (
 `interestid` int(11) NOT NULL,`interestname` varchar(255) DEFAULT NULL,PRIMARY KEY (`interestid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

其中user表用於記錄使用者資訊,interests表用於維護所有的興趣標籤,而userinterests用於維護每個使用者的興趣情況。

這時候,如果我們需要根據使用者id去查詢使用者的資訊和興趣資訊該怎麼做呢?這時候我們就要用到<select>中的另一個重要屬性了,那就是resultMap。

在配置查詢的返回結果時,resultType和resultMap是二選一的操作。對於比較複雜的查詢結果,一般都會設定成resultMap。

resultMap該怎麼配置呢?又支援哪些配置呢?我們看看下面:

<resultMap type="" id="">
  
    <!-- id,唯一性,注意啦,這個id用於標示這個javabean物件的唯一性, 不一定會是資料庫的主鍵(不要把它理解為資料庫對應表的主鍵) 
      property屬性對應javabean的屬性名,column對應資料庫表的列名
      (這樣,當javabean的屬性與資料庫對應表的列名不一致的時候,就能通過指定這個保持正常映射了)
    -->
    <id property="" column=""/>
    
    <!-- result與id相比, 對應普通屬性 -->  
    <result property="" column=""/>
    
    <!-- 
      constructor對應javabean中的構造方法
     -->
    <constructor>
      <!-- idArg 對應構造方法中的id引數 -->
      <idArg column=""/>
      <!-- arg 對應構造方法中的普通引數 -->
      <arg column=""/>
    </constructor>
    
    <!-- 
      collection,對應javabean中容器型別,是實現一對多的關鍵 
      property 為javabean中容器對應欄位名
      column 為體現在資料庫中列名
      ofType 就是指定javabean中容器指定的型別
    -->
    <collection property="" column="" ofType=""></collection>
    
    <!-- 
      association 為關聯關係,是實現N對一的關鍵。
      property 為javabean中容器對應欄位名
      column 為體現在資料庫中列名
      javaType 指定關聯的型別
     -->
    <association property="" column="" javaType=""></association>
</resultMap>

根據上面的說明,我們來看看之前的問題怎麼解決?

先截圖給出三個表的資料情況:

Mybatis中Mapper對映檔案使用詳解

Mybatis中Mapper對映檔案使用詳解

Mybatis中Mapper對映檔案使用詳解

接著,我們來定義興趣類,並改寫之前的使用者實體類

package com.majing.learning.mybatis.entity;

public class Interests {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Interests [id=" + id + ",name=" + name + "]";
	}	
}
package com.majing.learning.mybatis.entity;
 
import java.util.List;
 
public class User2 {
	private int id;
	private String name;
	private String password;
	private int age;
	private List<Interests> interests;
	private String author;
	
	public List<Interests> getInterests() {
		return interests;
	}
	public void setInterests(List<Interests> interests) {
		this.interests = interests;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User2 [id=" + id + ",name=" + name + ",password=" + password + ",age=" + age + ",interests=" + interests + ",author=" + author + "]";
	}
	
}

緊接著,我們改寫Dao介面:

package com.majing.learning.mybatis.dao;
 
import com.majing.learning.mybatis.entity.User2;
 
public interface UserDao2 {
	/**
	 * 查詢
	 * @param userId
	 * @return
	 */
	User2 findUserById (int userId);
}

然後,我們給相關實體類建立一下別名:

<typeAliases>
		<typeAlias alias="UserWithInterests" type="com.majing.learning.mybatis.entity.User2"/>
		<typeAlias alias="Interests" type="com.majing.learning.mybatis.entity.Interests"/>
</typeAliases>

然後再建立一個對應跟UserDao2對應的Mapper對映檔案:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" 
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.majing.learning.mybatis.dao.UserDao2">
 
	<resultMap type="UserWithInterests" id="UserWithInterestsMap">
		<id property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="password" column="password"/>
		<result property="age" column="age"/>
		<collection property="interests" column="interestname" ofType="Interests">
			<id property="id" column="interestid"/>
			<result property="name" column="interestname"/>
		</collection>
	</resultMap>
 
	<select id="findUserById" resultMap="UserWithInterestsMap">
		select a.*,c.* from user as a right join userinterests as b on a.id = b.userid right join interests as c on b.interestid = c.interestid where id = #{id}
	</select>
 
</mapper>

最後將這個對映檔案新增到<mappers>元素配置下:

<mappers>
		<mapper resource="com\majing\learning\mybatis\dao\UserDaoMapper.xml" />
		<mapper resource="com\majing\learning\mybatis\dao\UserDao2Mapper.xml" />
</mappers>

下面我們來寫個測試程式碼來測試一下是否可以正常執行:

public class UserDaoTest3 {
	@Test
	public void testFindUserById(){
		SqlSession sqlSession = getSessionFactory().openSession(true); 
		UserDao2 userMapper = sqlSession.getMapper(UserDao2.class); 
 
		User2 user = userMapper.findUserById(10); 
		System.out.println("記錄為:"+user);
 
	}
 
	// Mybatis 通過SqlSessionFactory獲取SqlSession,然後才能通過SqlSession與資料庫進行互動
	private static SqlSessionFactory getSessionFactory() {
		SqlSessionFactory sessionFactory = null;
		String resource = "configuration.xml";
		try {
			sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sessionFactory;
	}
}

執行程式碼後,我們可以看到成功啦!

Mybatis中Mapper對映檔案使用詳解

(3)sql

sql元素的意義,在於我們可以定義一串SQL語句,其他的語句可以通過引用它而達到複用它的目的。因為平時用到的也不多,這裡就不多介紹了,感興趣的朋友可以自行查閱資料瞭解一下。

(4)cache、cache-ref

關於快取的這塊邏輯還沒有研究過,後面專門寫篇文章針對快取進行鍼對性的說明,敬請關注。

到此這篇關於Mybatis中Mapper對映檔案使用詳解的文章就介紹到這了,更多相關Mybatis Mapper對映檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!