Mybatis的使用(4)

1:解決實體類成員變數和資料庫表中欄位名稱不一致的問題:

方法1:在寫sql語句時,給表中的列名起別名,名字和實體類名稱一樣

方法2:使用resultMap來解決:

例如:實體類中成員變數為id,name,資料庫表中的列名叫bookid,bookname,兩者不一致則使用resultmap:

List<Book> getall();

    <resultMap id="bookmap" type="book">
<!-- 主鍵綁定-->
<id property="id" column="bookid"></id>
<!-- 非主鍵綁定-->
<result property="name" column="bookname"></result>
</resultMap>
<select id="getall" resultMap="bookmap">
select bookid,bookname from book
</select>

 

表的關聯關係:一對多,多對一,一對一,多對多等關聯關係

資料庫中有兩張表,分別為student和teacher

 

 

 

 

一對多關係:(一個老師對應多個學生)

Teacher getById(Integer id);

    <resultMap id="teachermap" type="teacher">
<!-- 主鍵綁定-->
<id property="id" column="teid"></id>
<!-- 非主鍵綁定-->
<result property="name" column="tname"></result>
<!-- student實體類綁定,由於為List類型,所以-->

<collection property="students" ofType="student">
<!-- student中主鍵綁定-->
<id property="id" column="sid"></id>
<!-- stduent中非主鍵綁定-->
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>

<select id="getById" parameterType="int" resultMap="teachermap">
SELECT s.id sid, s.name sname, tid, t.id teid,t.name tname
FROM teacher t left JOIN student s ON s.tid=t.id
WHERE t.id=1
</select>



Teacher byId = teacherMapper.getById(1);
System.out.println(byId);

多對一關係:

Student getbyid(Integer id);


<mapper namespace="com.ztb.dao.StudentMapper">

<resultMap id="studentmap" type="student">
<!-- 主鍵綁定-->
<id property="id" column="sid"></id>
<!-- 非主鍵綁定-->
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>

<association property="teacher" javaType="teacher">
<id property="id" column="teid"></id>
<result property="name" column="tname"></result>
</association>

</resultMap>

<select id="getbyid" parameterType="int" resultMap="studentmap">
SELECT s.id sid, s.name sname, tid, t.id teid,t.name tname
FROM teacher t LEFT JOIN student s ON s.tid=t.id
WHERE s.id=#{id}
</select>




Student byId = studentMapper.getbyid(1);
System.out.println(byId);

 

一對一與上兩個類似

多對多關係需要有個第三張表來表示兩表之間的關係。

總之無論是什麼關聯關係,如果某方持有另一方的集合,則使用<collection>標籤完成映射,如果某方持有另一方的對象,則使用<association>標籤完成映射。

 

2:事務:多個操作同時完成,或同時失敗稱為事務處理

四個特性:原子性,一致性,隔離性,持久性

 

在mybatis中設置事務:

<transactionManager type=”JDBC”/>:程式設計師自己控制處理的提交和回滾

可以設置為自動提交:

sqlsession=factory.openSession():默認是手動提交,設置為false也是手動提交

sqlsession=factory.openSession(true):自動提交,不必再寫sqlsession.commit().

 

 

3:快取:mybatis框架提供兩級快取,一級快取和二級快取,默認開啟一級快取

快取的目的就是為了提高查詢效率

流程:先到快取里查,查不到的就去資料庫查,查完放快取里,下次在查詢的時候直接從快取里取,不在訪問資料庫。如果資料庫發生commit操作,則清空快取

一級快取使用的是sqlsession的作用域,同一個sqlsession共享一級快取的數據

二級快取使用的是mapper的作用域,不同的sqlsession只要訪問的是同一個mapper.xml文件,則共享二級快取作用域

二級快取步驟:

3.1在核心配置文件中加入

<setting name=”cacheEnabled” value=”true”/>

3.2.在mapper.xml中開啟二級快取

<cache></cache>

3.3實體類必須實現java.io.serializable,保證實體可序列化