首頁  >  文章  >  Java  >  MyBatis入門(五)---延時載入、快取

MyBatis入門(五)---延時載入、快取

黄舟
黄舟原創
2016-12-21 14:34:161268瀏覽

一、建立資料庫

1.1、建立資料庫

 


/*SQLyog EnterPRise v12.09(64 位元)MySQL - 5.7.9-log :資料庫- mybatis
************************** ****** ******************************************** **//*!40101 設定名稱utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 *OLD;//*40014 SET =@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!401111 SET @NO資料庫/*!32312 如果不存在*/`mybatis` /*!40100 預設字元集utf8 */;USE `mybatis`;/*表`author` 的表結構*/DROP TABLE IF EXISTS `author`;CREATE TABLE `author` (
 `author_id` int(11) unsigned NOT NULL AUTO_INCRMENT COMMENT '作者ID主鍵',
 `author_username` varchar(30) NOT NULL COMMENT '作者用戶名',2 N COMMENT '作者密碼',
 ` author_email` varchar(50) NOT NULL COMMENT '作者郵箱',
 `author_bio` varchar(1000) DEFAULT '這傢伙,賴什麼也留下' COMMENT '作者簡介',`register time ` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '註冊時間', PRIMARY KEY (`author_id`)
) ENGINE=InnoDB AUTO_INCRMENT=11 DEFAULT CHARSET=utf8;/*表格`author` 的資料* `author_username`,` author_password`,`author_email`,`author_bio`,`register_time`) values (1,'張三','123456','123@QQ.com','張三是個新手,剛開始註冊','2015- 10-29 10:23:59'),(2,'李四','123asf','lisi@163.com','魂牽夢融合','2015-10-29 10 :24:29'),( 3,'王五','dfsd342','ww@sina.com','康熙王朝','2015-10-29 10:25:23'),(4,'趙六','123098sdfa', 'zhaoliu@qq.com','花午骨','2015-10-29 10:26:09'),(5,'錢七','zxasqw','qianqi @qq.com','這傢伙很賴,什麼也沒留下','2015-10-29 10:27:04'),(6,'張三豐','123456','zhangsf@qq. com','這傢伙很賴,什麼也沒留下','2015-10-29 11:48:00'),(7,'張無忌','qwertuiop','wuji@163.com','這傢伙很賴,什麼也不留下','2015-10-29 11:48:24'),(8,'fdsf','ffff','fdsfds',NULL,NULL),(9,' fdsf','ffff','fdsfds ',NULL,NULL),(10,'aaaa','bbbb','ddd@qq.com','這傢伙很賴,什麼也沒留下','2015 -10-29 22:07:45 ');/*表格`blog` 的表格結構*/DROP TABLE IF EXISTS `blog`;CREATE TABLE `blog` (
 `blog_id` int(11) unsigned NOT NULL AUTO_INCRMENT COMM_id` int(11) unsigned NOT NULL AUTO_INCRMENT COMMENT 'BlogId 主鍵',
 `blog_title` varchar(255) NOT NULL COMMENT '部落格標題',
 `author_id` int(11) unsigned NOT NULL COMMENT '作者ID外鍵',  PRIMARY KEY (`blog_`id`) ( fk_author_id` (`author_id`), CONSTRAINT `fk_author_id` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`)
) ENGINE=InnoDB AUTO_INCliterENT=6author_id`)
) ENGINE=InnoDB AUTO_INCliterENT=6 /insert  into `blog`(` blog_id`,`blog_title`,`author_id`) values (1,'小張的部落格',1),(2,'小李',2),(3,'王五不是人',3),( 4,'趙地人',4),(5,'錢錢錢',5);/*表`posts`的表結構*/DROP TABLE IF EXISTS `posts`; CREATE TABLE `posts` (
 ` post_id` int(11) unsigned NOT NULL AUTO_INCRMENT COMMENT '文章主鍵ID',
 `post_subject` varchar(255) NOT NULL COMMENT '文章主題, COMMENT '最大3000個內容內容',
 `blog_id` int(11) unsigned NOT NULL COMMENT '博客主鍵做外鍵',
 `createtime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '``createtime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '``Y. KEY `fk_blog_id` (` blog_id`), 約束`fk_blog_id` 外鍵(`blog_id`) 引用`blog` (`blog_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;/*Data for the table `posts` */insert  into `posts`(`post_id`,`post_subject`,`post_body`,`blog_id`,`createtime`. (1,'Mybatis入門一','什麼是MyBatis ?rnMyBatis 是支援客製化SQL、預存程序以及高級映射的優秀的持久層框架。MyBatis 避免了幾乎所有的JDBC 程式碼和手動設定參數以及取得結果集。 MyBatis 可以對配置和原生Map使用簡單的xml 或註解,將介面和java 的POJOs(Plain Old Java Objects,普通的Java物件)映射成資料庫中的記錄。 32:21'),(2,'Mybatis入門二','要使用MyBatis, 只需將mybatis-x.x.x.jar 檔案置於classpath 中即可。',1,'2015-10-29 10:32:52 '),(3,'Oracle學習','Oracle Database,又稱為Oracle RDBMS,或簡稱Oracle。是甲骨文公司的關聯式資料庫管理系統',2,'2015-10-29 10:33:26' ),(4,'JAVA學習一','Java是由Sun Microsystems公司於1995年5月推出的Java物件導向程式設計語言和Java平台的總稱',3,'2015-10-29 10:34: 17'),(5,'PL/SQL','PL/SQL也是一種程式語言,叫做過程化SQL語言(Procedural Language/SQL)。PL/SQL是Oracle資料庫對SQL語句的擴展',4, '2015-10-29 10:37:52'),(6,'CSS標籤選擇器','標籤選擇器rnID選擇器rn類選擇器rn特殊選擇器',5,'2015-10-29 10 :39:44'),(7,'javascript','js:是前端腳本語言',2,'2015-10-29 10:40:18');/*!40101 SET SQL_MODE=@OLD_SQL_MODE */ ;/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */SQL/*!40111 SETSQL_NOTES=@UNIQUE_CHECKS */SQL*

 

二、建立專案

2.1、建立專案

 

三、建立實體類別與Mapper介面

3.1、3個實體類別

.util.Date;/**

*

* @ClassName: Author

* @Description: TODO(作者)

* @author 劉劉 劉劉南* @date 2015-10-3112:39:333312:39:333112:39*/public class Author {    //作者id

   private Integer authorId;    //作者姓名
   private String authorUserName;作者信箱
   private String authorEmail;    //作者介紹
   private String authroBio;    //註冊時間
   private Date registerTime;    
   private Date registerTime;    
   private Date registerTime;   return authorId;
   }    public void setAuthorId(Integer authorId) {        this.authorId = authorId;
}    public String getAuthorUserName() {        return authorUserName;
   }    public void setAuthorUserName(String authorUser") { AuthorPassword() {        return authorPassword;
   }    public void setAuthorPassword(String authorPassword) {       this.authorPassword(String authorPassword) {       this.authorPassword = authorPassword;
   }    public String getAuthorEmail() {        return authorEmail;
   }    public v.   }    public String getAuthroBio() {        return authroBio;
   }    public void setAuthroBio(String authroBio) {        this.authroBio = authroBio;
   }    public Date getRegisterTime() {        return registerTime; = registerTime;
   }
   @Override    public String toString() {        return "Author [authorId =" + authorId + ", authorUserName="
               + authorUserName + ", authorPassword=" + authorPassword      hormail +o + ammo + a​​vol ​​oolPassword=" + authorPassword      horo +a + ammo + ​​oge, the   ​​褐@@ + ammo + coo ​​Let,"           + ", registerTime=" + registerTime + "]";
   }
   
   
}


 

 

package com.pb.mybatis.po;import java.util.List;public class Blog {    
   //Blog,ID
   private Integer blogId;   詞//   //作者
   私人作者author;    // 文章列表
   private IntegerauthorId;    
   //文章列表
 {        return blogId;
   }    public void setBlogId(Integer blogId) {        this .blogId = blogId;
   }    public String getBlogTitle() {        return blogTitle;
   }    public void setBlogTitle(String blog )  }    public Author getAuthor() {        returnauthor;
   }    public void setAuthor(Author writer ) {        this.author = 作者;
   }    public Integer getAuthorId() {        returnauthorId;hor>this. horId;
   }    公共清單; getPostsList() {        return postsList;
   } public void setPostsList(List postsList) {        this.postsList = postsList;
   }
   
  blogId + “ , blogTitle=" + blogTitle                +  ", authorId=" +authorId + "]";
   }
   
 

   
   
 pop.匯入java.util.Date ;public class Posts {    //文章ID
   private Integer postId;    // 文章標題
   private String postTitle;    // 文章主體內容
   private String postBody; ;    //建立時間
   private Date createTime;    
   
   public Integer getPostId() {        return postId;
   }    public void setPostId(Integer postId) {        this.postId = postIdtle
   }    public void setPostTitle(String postTitle) {        this. postTitle = postTitle;
   }    public String getPostBody() {        return postBody;

   }    public void setPostBody(String postBody) {       this.postBody = postBody;   return createTime;

   }    public void setCreateTime(Date createTime ) {        this.createTime = createTime ;

   }    

   
   public Integer getBlogId() {        return blogId;
 
 }
   @Override    public String toString() {        return "貼文[postid =「 + postid +”,posttitle =“ + posttitle +”,postbody =“ + postbody +”,casteTime =“ + castement +”,blogid =“ + blogid +”];
   
   
}


、3個介面

 

package com.pb.mybatis.mapper;import com.pb.mybatis.po.Author;公共介面AuthorMapper {    /**
    *
   
   * @Title: findAuthorById
   
   * @Description: TODO(依id) @param) @return    設定檔
   
   * @return Author      
   * @return Author    返回型別
   
   * @ throws
   */
   public Author findAuthorById(int id); com.pb.mybatis.mapper;導入com.pb.mybatis.po.Blog;公共介面BlogMapper {    
   /**
    *
   
   * @Title: findBlogById

   

   * @Description: TODO( id

   * @param @return    設定文件

   
   * @return Blog    回傳類型
   
   * @throws
   */
   公共部落格com.pb.mybatis.mapper;導入java.util.List;導入com.pb.mybatis.po.Posts;公共介面PostsMapper {    /**
    *
   
   * @Title: findPostsByBlogId
   
   * @Description: TODO(根據BLOGID 查找列表) * @param @return    設定檔
   
   * @return List    返回型式
   
   * @throws
   */
   public List; findPostsBblogyBlogId(int blogyBId) ;
}

 

 

 

 

、四建立mapper.xml與confinguration.xml

4.1、相對應的mapper.xml與confinguration.xml

4.1、相對應的mapperxml.
br/>  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/ dtd/mybatis-3-mapper .dtd">

 

 

.

br/>  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/ dtd/mybatis-3-mapper.dtd">
 

PostsMapper.xml

 

/p>  PUBLIC "-//mybatis.org// "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 


.properties

 

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mybatis?character=utf8🜎時加載,同時關閉立即加載

 


   
   
    !--資料來源 ->
   
   
    豆name="username" value="${username}"/>
   
   



 

 

 

 

套件com.pb.mybatis.mapper;導入java.io.InputStream;導入java.util.List;導入org.apache.ibatis.io.Resources;導入org.apache.ibatis.session.SqlSession;導入org.apache .ibatis.session.SqlSessionFactory;導入org.apache.ibatis.session.SqlSessionFactoryBuilder;導入org.junit.Before;導入org.junit.Test;導入com.pb.mybatis.po.Blog;導入com.pb.mybatis。 po.Posts;public class BlogMapperTest {    private SqlSessionFactory sqlSessionFactory;

   @Before    public void setUp() throws Exception {
xml  public void  InputStream resource=Resources.getResourceAsStream(config);
     sqlSessionFactory=新SqlSessionFactoryBuilder ().build(resource);
   }    /**
    *
   
   * @Title: testFindBlogs
   
   * @Description: TODO(延遲載入)
   * @Description: TODO(延遲
   * @return void    回傳型
   
   * @throws
   */
   @Test    public void testFindBlogById() {    sqlion open////////「 ion();        //取得Mapper介面物件
       BlogMapper blogMapper =sqlSession。 +blog.getBlogTitle( ));
       System.out.println( "==========開始延遲載入authorAuthor===========");
       System.out.println(blog.getAuthor( ));
       System.out .println("==========開始延遲載入文章===========");
       List;清單=blog.getPostsList ();        /*int count=0;
       for(貼文p:list){
           System.out.println("count+"+count++); Id());
           System. out.println (p.getPostTitle());
           System.out.println(p.getPostBody());
       System.out.println(p.getBlogId( ));
       }*/
       
   }

}


 ==
. =?調試[主要] - ==>參數:1(Integer)
DEBUG [main] - 1...小張的部落格===========開始延遲載入作者作者===== === ===調試[主要] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數: 1(Integer)
DEBUG [main] - ;  準備:從blog_id=? 的貼文中選擇*?調試[主要] - ==>參數: 1(Integer)
DEBUG [main] -

 

六、一級快取

6.1、mybatbatisbat了一級緩存,sqlSession中預設有一個hashMap


當查詢時,先去hashMap中查找,

如果有就直接,取出,不再操作資料庫

如果沒有就去資料庫查找,並放在haspMap中

當做事情時,如添加,刪除,修改,有commit時會清空一級伺服器

當做事情時,如添加,刪除,修改,有commit時會清空一級伺服器

sqlSession是互不影響的,一級伺服器

 

6.2、還是上級的例子

 

6.2、還是上級的範例查詢用戶

 MyBatis入門(五)---延時載入、快取

套件com.pb.mybatis.mapper;導入靜態org.junit.Assert.*;導入java.io.InputStream;導入org.apache.ibatis.io.Resources;導入org.apache.ibatis.session.SqlSession; org.apache.ibatis.session.SqlSessionFactory;導入org.apache.ibatis.session.SqlSessionFactoryBuilder;導入org.junit.Before;導入org.junit.Test;導入com.pb.mybatis.po.Author;公共類別AuthorMapperTapper private SqlSessionFactory sqlSessionFactory;

   @Before    public void setUp() throws Exception {
     
       sqlSessionFactory=new SqlSessionFactoryBuilder ().build(資源);
   }

   @Test    public void testFindAuthorById() {        //獲取會話工廠
 sqlion open AuthorMapperauthorMapper=sqlSession.getMapper(AuthorMapper.class);        //第一次查詢
       作者author1=authorMapper .findAuthorById(2);
       System.out.println(author1);        //再查詢相同的
       Author writer2aut.Mapper w. out.println(author2);        
       //再詢問不一樣的
     作者author3=authorMapper.findAuthorById(4);
       System.out.println(author3);
 }



結果:

 

調試[主要] - ==>準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數: 2(Integer)

DEBUG [main] - 作者[authorId=2,authorUserName=李四,authorPassword=123asf,authorEmail=lisi@163.com,authroBiok=word=123asf,authorEmail=lisi@163.com,authroBio=word=word registerTime=Thu Oct 29 10:24:29 CST 2015]調試[主] - ==>  準備:從作者中選擇*,其中author_id=?調試[主] - ==>參數:4(Integer)

DEBUG [main] -

 

 


 

6.3、當查詢後,做事務,再查詢一次

 

/**

    *

   

   * @Title: addAuthor

   

   * @Description: TODO(新增)

param   para     設定檔

   

   * @return int    回傳型別

   

   * @throws

*/
   public int addAuthor(作者作者);


 

 

 

mapper.xml中做同樣的選擇

 

插入作者(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorhor},{mail ,#{ authroBio})插入>

 

 

 

測試

 

套件com.pb.mybatis.mapper;導入靜態org.junit.Assert.*;導入java.io.InputStream;導入org.apache.ibatis.io.Resources;導入org.apache.ibatis.session.SqlSession導入; org.apache.ibatis.session.SqlSessionFactory;導入org.apache.ibatis.session.SqlSessionFactoryBuilder;導入org.junit.Before;導入org.junit.Test;導入com.pb.mybatis.po.Author;公共類別AuthorMapperTapper private SqlSessionFactory sqlSessionFactory;

   @Before    public void setUp() throws Exception {
     
       sqlSessionFactory=new SqlSessionFactoryBuilder ().build(資源);
   }

   @Test    public void testFindAuthorById() {        //獲取會話工廠
 sqlion open AuthorMapperauthorMapper=sqlSession.getMapper(AuthorMapper.class);        //第一次查詢
       作者author1=authorMapper .findAuthorById(2);
       System.out.println(author1);
       System.out.println("==========下方有事務處理==== ===="); =new Author();
       newAuthor.setAuthorEmail("qq.com@qq.com");
       newAuthor.setAuthorPassword("fdsfds");
       newAuthor.setAuthroBio("射雕英雄傳");        int num=authorMapper.addAuthor(newAuthor);
       sqlSession.commit();
             System.out.println("num="+num );
       System. out.println("再查詢");        //再查詢相同的
       作者author2=authorMapper.findAuthorBaut.2);
   
   }

   

}


 

 

 

結果:

 

[主要] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數: 2(Integer)

DEBUG [main] -  準備:插入作者(作者用戶名,作者密碼,作者電子郵件,作者生物)值(?,?,?,?)

DEBUG [main] - ==>參數:郭靖(String)、fdsfds(String)、qq.com @qq.com(String)、射雕英雄傳(String)

DEBUG [main] - DEBUG [main] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數: 2(Integer)

DEBUG [main] -


 

 

 

 .

sqlSession不互不影響的,一級伺服器

Mapper(namespace)是一級伺服器

多個sqlSession可以共享一個Mapper的二級伺服器區域

二級伺服器按namespace自己的二級伺服器區域namespace

第一個namespace的mapper都有一個二級伺服器區域,2個mapper的namespace如果相同,這2個mapper執行sql查詢資料將存在相同的二級伺服器區域中。

 MyBatis入門(五)---延時載入、快取

7.2、開啟二級伺服器

1.二級伺服器是mapper範圍等級的,除了在configuration.xml設定二級伺服器的總交換機,還在單獨的mapper.xml中開啟二級伺服器


 

2.mapper對就的pojo類,實現序列化

MyBatis入門(五)---延時載入、快取

3.在authorMapper中開啟二級緩存

 

 


.

@Test    public void testCache() {        // 取得會話工廠

       SqlSession sqlSession1 = sqlSession​​.openy.openSession(capper 1.getMapper(AuthorMapper.class);        // 第一次查詢

       Author author1 = authorMapper1. findAuthorById(2);        //必須關閉不資料無法寫入快取區域       sqlSession1.close();        // 取得會話工廠

open 

       AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class );

       sqlSession2.close();*/

       // 取得會話工廠
       SqlSession 系統apper3 = sqlSession3.getMapper(AuthorMapper.class);        // 第一次查詢
       Author author3 = authorMapper3.findAuthorById(2);
       sqlSession3.close();
   }


 

DEBUG [


 Opening JDBC Connection
DEBUG [main] - Created connection 873769339.

DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4lig@3414a97b]

DEBUG Connectionbc.JDBC4man@3414a97b]

DEBUG [Connectionbc.JDBC. author_id=? DEBUG [main] - ==> Parameters: 2(Integer)

DEBUG [main] - DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - Returned connection 873769339 to pool.
DEBUG [maindm. .AuthorMapper]: 0.5


中間增加commit作業

@Test    public void testCache() {        // 取得會話工廠

          AuthorMapper authorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // 第一次查詢

       Author author1 = authorMapper1.findAuthorById(2);        //必須關閉不資料無法寫入快取區域    SqlSession sqlSession2 = sqlSessionFactory.openSession();

AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class);

       Author author2 = authorMapper2.findAuthorById(2); hor   com 
       author2.setAuthroBio("公司");
       authorMapper2. updateAuthor(author2);        //commit會清空緩存區域       sqlSession2.commit();
       sqlSession3 = sqlSessionFactory.openSession();
       AuthorMapper authorMapper3 = sqlSession3.getMapper(AuthorMapper. class);        // 第一個查詢
       Author author3 = authorMapper3.findAuthorById(2);
   }  SessorById(2);
   }  Session3.close);

DEBUG [main] - 快取命中率[com.pb.mybatis.mapper.AuthorMapper]: 0.0DEBUG [main] - 開啟JDBC 連線
DEBUG [main] - 建立連線873769339.
DEBUG [main] - 將自動提交設定為false關於JDBC 連接[com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數:2(整數)
DEBUG [main] - DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - 返回連接873769339 到池。
DEBUG [main] - 快取命中率 [com.pb.mybatis.mapper.AuthorMapper]: 0.5DEBUG [main] -開啟 JDBC 連線
DEBUG [main] - 從池中簽出連線 873769339。
DEBUG [main] - 在JDBC 連線上將自動提交設定為false [com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - ==>  準備:更新作者SETauthor_username=?,,horhor kipmail=,, ==> ?,author_bio=?,register_time=?其中author_id=?調試[主要] - ==>參數: 董事長(String), 123asf(String), lisi@163.com(String), 公司(String), 2015-10-29 10:24:29.0(Timestamp), 2 (Integer)
DEBUG [main] - DEBUG [主要] - 將JDBC 連線上的自動提交重設為true [com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - 回傳連線到連線到連線池。
DEBUG [main] - 快取命中率 [com.pb.mybatis.mapper。 AuthorMapper]: 0.3333333333333333DEBUG [main] - 開啟 JDBC 連線
DEBUG [main] - 從池簽出連線 873769339。
DEBUG [main] - 在 JDBC 連接上將自動提交設定為 false [com.mysql.jdbc.JDBC4Connection@3414a97b]
調試 [主要] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數:2(整數)
DEBUG [main] - DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - 返回連接873769339 到池。

 

八、Mybatis 與ehcache 整合

8.1、把jar 套件放入專案

MyBatis入門(五)---延時載入、快取

8.2、建立ehcache.xml

="http: //www.w3.org/2001/XMLSchema-instance"

   xsi:noNamespaceSchemaLocation="../config/ehcache. xsd">

   🎠 Element 0 "

       maxElementsOnDisk="10000000"

       eternal="false"

           timeToLiveSeconds="120"
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="LRU">
   memoryStoreEvictionPolicy="LRU">
ache /ehcache>


 

 

 

8.3、mapper的快取中指定type

 

 

 

 


8.4、測試

 

8.4、測試

@Test    public void testCache() {        // 取得會話工廠
       SqlSession sqlSession1 = sqlSessionFactory.openSession(Bautor); apper(AuthorMapper.class);        // 第一次查詢
       Author author1 = authorMapper1.findAuthorById (2);        //必須關閉不資料無法寫入快取區域       sqlSession1.close();        // 取得會話工廠
     AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class);
Author author2 = authorMapper2.findAuthorById(2);        //更新
       author2.setAuthorUserName("董事長" ); horMapper2.updateAuthor(author2);        //commit會清空快取區域       sqlSession2 .commit();
       sqlSession2.close();        // 取得會話工廠
       SqlSession sqlSession3 = openSessionFactory.Sess = sqlSession3.getMapper(AuthorMapper.class);        // 第一次查詢
       Author author3 = authorMapper3.findAuthorById(2);
       sqlSession3.close();
   }


 

DEBUG [main] - 從類別路徑找到的ehcache.xml 設定ehcache:file:/E:/mywork/MybatisDemo2/bin/ehcache.xml
DEBUG [main] - 從URL 設定ehcache:file:/E:/ mywork /MybatisDemo2/bin/ehcache.xml
DEBUG [main] - 從InputStream 設定ehcache
DEBUG [main] - 忽略ehcache 屬性xmlns:xsi
DEBUG [main] - 忽略ehcache 屬性xsi:noNamespaceemaLocation [nnoNamespaceBUGation [儲存路徑:F:developehcache
DEBUG [main] - 使用預設設定建立新的CacheManager
DEBUG [main] -propertiesString 為null。
DEBUG [main] - 未指定 CacheManagerEventListenerFactory 類別。正在跳過...
DEBUG [main] - 未指定 BootstrapCacheLoaderFactory 類別。正在跳過...
DEBUG [main] - CacheWriter 工廠未配置。正在跳過...
DEBUG [main] - 未指定 CacheExceptionHandlerFactory 類別。跳過...
DEBUG [main] - 為com.pb.mybatis.mapper.AuthorMapper
DEBUG 初始化net.sf.ehcache.store.NotifyingMemoryStore [main] - 初始化快取:com.pb.mybatis.mapper.AuthorMapper
DEBUG [main] - CacheDecoratorFactory 未配置為defaultCache。跳過 'com.pb.mybatis.mapper.AuthorMapper'。
DEBUG [main] - 快取命中率 [com.pb.mybatis.mapper.AuthorMapper]: 0.0DEBUG [main] - 開啟 JDBC 連線
DEBUG [main] -建立了連線 1286943672。
DEBUG [main] - 在 JDBC 連接上將 autocommit 設定為 false [com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數:2(整數)
DEBUG [main] - DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - 返回連接1286943672 到池。
DEBUG [main] - 快取命中率 [com.pb.mybatis.mapper.AuthorMapper]: 0.5DEBUG [main] -開啟 JDBC 連線
DEBUG [main] - 從池中簽出連線 1286943672。
DEBUG [main] - 在JDBC 連線上將自動提交設定為false [com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - ==>  準備:更新作者SETauthor_username=?,horhorDEBUG [main] - ==>  準備:更新作者SETauthor_username=?,horhor_hormail=,, i ?,author_bio=?,register_time=?其中author_id=?調試[主要] - ==>參數: 董事長(String), 123asf(String), lisi@163.com(String), 公司(String), 2015-10-29 10:24:29.0(Timestamp), 2 (Integer)
DEBUG [main] - DEBUG [main] - 將JDBC 連線上的自動提交重設為true [com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - 返回連接池到連接池。
DEBUG [main] - 快取命中率 [com.pb.mybatis.mapper。 AuthorMapper]: 0.3333333333333333DEBUG [main] - 開啟 JDBC 連線
DEBUG [main] - 從池簽出連線 1286943672。
DEBUG [main] - 在 JDBC 連接上將自動提交設定為 false [com.mysql.jdbc.JDBC4Connection@4cb533b8]
調試 [主要] - ==>  準備:從作者中選擇*,其中author_id=?調試[主要] - ==>參數:2(整數)
DEBUG [main] - DEBUG [main] - 關閉JDBC 連線[com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - 返回連接1286943672到池。

 以上是MyBatis入門(五)---延遲載入、快取的內容,更多相關請內容關注PHP中文網(www.php.cn)! 


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn