1.一、創建數據庫 html
2.一、建立項目 java
3.一、3個實體類 mysql
package com.pb.mybatis.po; import java.util.Date; /** * * @ClassName: Author * @Description: TODO(做者) * @author 劉楠 * @date 2015-10-31 下午12:39:33 * */ public class Author { //做者id private Integer authorId; //做者姓名 private String authorUserName; //做者密碼 private String authorPassword; //做者郵箱 private String authorEmail; //做者介紹 private String authroBio; //註冊時間 private Date registerTime; public Integer getAuthorId() { return authorId; } public void setAuthorId(Integer authorId) { this.authorId = authorId; } public String getAuthorUserName() { return authorUserName; } public void setAuthorUserName(String authorUserName) { this.authorUserName = authorUserName; } public String getAuthorPassword() { return authorPassword; } public void setAuthorPassword(String authorPassword) { this.authorPassword = authorPassword; } public String getAuthorEmail() { return authorEmail; } public void setAuthorEmail(String authorEmail) { this.authorEmail = authorEmail; } public String getAuthroBio() { return authroBio; } public void setAuthroBio(String authroBio) { this.authroBio = authroBio; } public Date getRegisterTime() { return registerTime; } public void setRegisterTime(Date registerTime) { this.registerTime = registerTime; } @Override public String toString() { return "Author [authorId=" + authorId + ", authorUserName=" + authorUserName + ", authorPassword=" + authorPassword + ", authorEmail=" + authorEmail + ", authroBio=" + authroBio + ", registerTime=" + registerTime + "]"; } }
package com.pb.mybatis.po; import java.util.List; public class Blog { //Blog,ID private Integer blogId; //Blog 名稱標題 private String blogTitle; //外鍵authorId //做者 private Author author; //文章 列表 private Integer authorId; //文章列表 private List<Posts> postsList; public Integer getBlogId() { return blogId; } public void setBlogId(Integer blogId) { this.blogId = blogId; } public String getBlogTitle() { return blogTitle; } public void setBlogTitle(String blogTitle) { this.blogTitle = blogTitle; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Integer getAuthorId() { return authorId; } public void setAuthorId(Integer authorId) { this.authorId = authorId; } public List<Posts> getPostsList() { return postsList; } public void setPostsList(List<Posts> postsList) { this.postsList = postsList; } @Override public String toString() { return "Blog [blogId=" + blogId + ", blogTitle=" + blogTitle + ", authorId=" + authorId + "]"; } }
package com.pb.mybatis.po; import java.util.Date; public class Posts { //文章ID private Integer postId; //文章標題 private String postTitle; //文章主體內容 private String postBody; //外鍵 private Integer blogId; //創建時間 private Date createTime; public Integer getPostId() { return postId; } public void setPostId(Integer postId) { this.postId = postId; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public String getPostBody() { return postBody; } public void setPostBody(String postBody) { this.postBody = postBody; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getBlogId() { return blogId; } public void setBlogId(Integer blogId) { this.blogId = blogId; } @Override public String toString() { return "Posts [postId=" + postId + ", postTitle=" + postTitle + ", postBody=" + postBody + ", createTime=" + createTime + ", blogId=" + blogId + "]"; } }
3.二、3個接口 sql
package com.pb.mybatis.mapper; import com.pb.mybatis.po.Author; public interface AuthorMapper { /** * * @Title: findAuthorById * @Description: TODO(根據id查找) * @param @param id * @param @return 設定文件 * @return Author 返回類型 * @throws */ public Author findAuthorById(int id); }
package com.pb.mybatis.mapper; import com.pb.mybatis.po.Blog; public interface BlogMapper { /** * * @Title: findBlogById * @Description: TODO(根據BLOGID查找BLOG,並關聯author,與posts實現延時加載) * @param @param id * @param @return 設定文件 * @return Blog 返回類型 * @throws */ public Blog findBlogById(int blogId); }
package com.pb.mybatis.mapper; import java.util.List; import com.pb.mybatis.po.Posts; public interface PostsMapper { /** * * @Title: findPostsByBlogId * @Description: TODO(根據BLOGID查找文章列表) * @param @param blogId * @param @return 設定文件 * @return List<Posts> 返回類型 * @throws */ public List<Posts> findPostsByBlogId(int blogId); }
4.一、相對應的mapper.xml 數據庫
AuthorMapper.xml apache
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pb.mybatis.mapper.AuthorMapper"> <!--映射做者Author --> <resultMap type="Author" id="authorResultMap"> <id property="authorId" column="author_id"/> <result property="authorUserName" column="author_username"/> <result property="authorPassword" column="author_password"/> <result property="authorEmail" column="author_email"/> <result property="authroBio" column="author_bio"/> <result property="registerTime" column="register_time"/> </resultMap> <!-- 根據ID查找 --> <select id="findAuthorById" parameterType="int" resultMap="authorResultMap"> select * from author where author_id=#{id} </select> </mapper>
BlogMapper.xml 緩存
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pb.mybatis.mapper.BlogMapper"> <!--Blog映射 --> <resultMap type="Blog" id="blogResultMap"> <!--Blog映射 --> <id property="blogId" column="blog_id"/> <result property="blogTitle" column="blog_title"/> <result property="authorId" column="author_id"/> <!--一對一 --> <association property="author" javaType="Author" column="author_id" select="com.pb.mybatis.mapper.AuthorMapper.findAuthorById"/> <!--關聯做者 外鍵 column:外鍵 select:引用Authro的namespace.方法 --> <!--一對多 ofType屬性指定集合中元素的對象類型。--> <collection property="postsList" ofType="Posts" javaType="ArrayList" column="blog_id" select="com.pb.mybatis.mapper.PostsMapper.findPostsByBlogId"/> </resultMap> <!-- 根據ID查找 --> <select id="findBlogById" parameterType="int" resultMap="blogResultMap"> SELECT * FROM blog WHERE blog_id=#{blogId} </select> </mapper>
PostsMapper.xml session
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pb.mybatis.mapper.PostsMapper"> <!--映射做者文章 --> <resultMap type="Posts" id="postsResultMap"> <id property="postId" column="post_id"/> <result property="postTitle" column="post_subject"/> <result property="postBody" column="post_body"/> <result property="blogId" column="blog_id"/> <result property="createTime" column="createtime"/> </resultMap> <!-- 根據ID查找 --> <select id="findPostsByBlogId" parameterType="int" resultMap="postsResultMap"> select * from posts where blog_id=#{blogId} </select> </mapper>
4.二、configuration.xml mybatis
db.properties app
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?character=utf8 username=root password=root
開啓延時加載,同時關閉當即加載
<settings> <!--開啓延時加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!--關閉當即加載 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--資源文件 --> <properties resource="db.properties"/> <settings> <!--開啓延時加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!--關閉當即加載 --> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!-- 別名 --> <typeAliases> <!-- <typeAlias type="com.pb.mybatis.po.User" alias="User"/> --> <package name="com.pb.mybatis.po"/> </typeAliases> <!--配置 --> <environments default="development"> <environment id="development"> <!--事務 --> <transactionManager type="JDBC"/> <!--數據源 --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <package name="com.pb.mybatis.mapper"/> </mappers> </configuration>
5.一、JUNIT
package com.pb.mybatis.mapper; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.pb.mybatis.po.Blog; import com.pb.mybatis.po.Posts; public class BlogMapperTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { String config="configuration.xml"; InputStream resource=Resources.getResourceAsStream(config); sqlSessionFactory=new SqlSessionFactoryBuilder().build(resource); } /** * * @Title: testFindBlogs * @Description: TODO(延時加載) * @param 設定文件 * @return void 返回類型 * @throws */ @Test public void testFindBlogById() { //創建會話 SqlSession sqlSession=sqlSessionFactory.openSession(); //獲取Mapper接口對象 BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class); //調用Mapper方法 Blog blog=blogMapper.findBlogById(1); System.out.println(blog.getBlogId()+"..."+blog.getBlogTitle()); System.out.println("===========開始延時加載做者Author==========="); System.out.println(blog.getAuthor()); System.out.println("===========開始延時加載文章==========="); List<Posts> list=blog.getPostsList(); /*int count=0; for(Posts p:list){ System.out.println("count+"+count++); System.out.println(p.getPostId()); System.out.println(p.getPostTitle()); System.out.println(p.getPostBody()); System.out.println(p.getCreateTime()); System.out.println(p.getBlogId()); }*/ } }
結果:
DEBUG [main] - ==> Preparing: SELECT * FROM blog WHERE blog_id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1 1...小張的Blog ===========開始延時加載做者Author=========== DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1 Author [authorId=1, authorUserName=張三, authorPassword=123456, authorEmail=123@qq.com, authroBio=張三是個新手,剛開始註冊, registerTime=Thu Oct 29 10:23:59 CST 2015] ===========開始延時加載文章=========== DEBUG [main] - ==> Preparing: select * from posts where blog_id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 2
6.一、mybatis一級緩存
mybatis,默認開啓了一級緩存,sqlSession中默認有一個hashMap
當查詢時,先去hashMap中查找,
若是有就直接,取出,再也不操做數據庫
若是沒有就去數據庫查找,並放在haspMap中
當作事物時,如添加,刪除,修改,後有commit時會清空一級緩存
sqlSession是互不影響的,一級緩存
6.二、仍是上級的例子
測試:查詢用戶
package com.pb.mybatis.mapper; import static org.junit.Assert.*; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.pb.mybatis.po.Author; public class AuthorMapperTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { String config="configuration.xml"; InputStream resource=Resources.getResourceAsStream(config); sqlSessionFactory=new SqlSessionFactoryBuilder().build(resource); } @Test public void testFindAuthorById() { //獲取會話工廠 SqlSession sqlSession=sqlSessionFactory.openSession(); AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class); //第一次查詢 Author author1=authorMapper.findAuthorById(2); System.out.println(author1); //再次查詢一樣的 Author author2=authorMapper.findAuthorById(2); System.out.println(author2); //再次查詢不的一樣的 Author author3=authorMapper.findAuthorById(4); System.out.println(author3); } }
結果:
DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 Author [authorId=2, authorUserName=李四, authorPassword=123asf, authorEmail=lisi@163.com, authroBio=魂牽夢縈 , registerTime=Thu Oct 29 10:24:29 CST 2015] Author [authorId=2, authorUserName=李四, authorPassword=123asf, authorEmail=lisi@163.com, authroBio=魂牽夢縈 , registerTime=Thu Oct 29 10:24:29 CST 2015] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 4(Integer) DEBUG [main] - <== Total: 1 Author [authorId=4, authorUserName=趙六, authorPassword=123098sdfa, authorEmail=zhaoliu@qq.com, authroBio=花午骨, registerTime=Thu Oct 29 10:26:09 CST 2015]
6.三、當查詢後,作事務,再查詢第一次的
接口中作添加方法
/** * * @Title: addAuthor * @Description: TODO(添加) * @param @param author * @param @return 設定文件 * @return int 返回類型 * @throws */ public int addAuthor(Author author);
mapper.xml中作一樣的select
<!--添加 --> <insert id="addAuthor" parameterType="Author" useGeneratedKeys="true" keyProperty="authorId"> INSERT INTO author(author_username,author_password,author_email,author_bio) VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio}) </insert>
測試
package com.pb.mybatis.mapper; import static org.junit.Assert.*; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.pb.mybatis.po.Author; public class AuthorMapperTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { String config="configuration.xml"; InputStream resource=Resources.getResourceAsStream(config); sqlSessionFactory=new SqlSessionFactoryBuilder().build(resource); } @Test public void testFindAuthorById() { //獲取會話工廠 SqlSession sqlSession=sqlSessionFactory.openSession(); AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class); //第一次查詢 Author author1=authorMapper.findAuthorById(2); System.out.println(author1); System.out.println("=======下面有事務處理========"); Author newAuthor=new Author(); newAuthor.setAuthorEmail("qq.com@qq.com"); newAuthor.setAuthorPassword("fdsfds"); newAuthor.setAuthorUserName("郭靖"); newAuthor.setAuthroBio("射鵰英雄傳"); int num=authorMapper.addAuthor(newAuthor); sqlSession.commit(); System.out.println(newAuthor.getAuthorId()); System.out.println("num="+num); System.out.println("再次查詢"); //再次查詢一樣的 Author author2=authorMapper.findAuthorById(2); System.out.println(author2); } }
結果:
DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 Author [authorId=2, authorUserName=李四, authorPassword=123asf, authorEmail=lisi@163.com, authroBio=魂牽夢縈 , registerTime=Thu Oct 29 10:24:29 CST 2015] =======下面有事務處理======== DEBUG [main] - ==> Preparing: INSERT INTO author(author_username,author_password,author_email,author_bio) VALUES(?,?,?,?) DEBUG [main] - ==> Parameters: 郭靖(String), fdsfds(String), qq.com@qq.com(String), 射鵰英雄傳(String) DEBUG [main] - <== Updates: 1 DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@42bb0406] 11 num=1 再次查詢 DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 Author [authorId=2, authorUserName=李四, authorPassword=123asf, authorEmail=lisi@163.com, authroBio=魂牽夢縈 , registerTime=Thu Oct 29 10:24:29 CST 2015]
7.一、mybatis二級緩存與一級緩存
sqlSession是互不影響的,一級緩存
Mapper(namespace)是二級緩存
多個sqlSession能夠共享一個Mapper的二級緩存區域
二級緩存按namespace分,其它的mapper也有本身的二級緩存區域namespace
第一個namespace的mapper都有一個二級緩存區域,2個mapper的namespace若是相同,這2個mapper執行sql查詢數據將存在相同的二級緩存區域中.
7.二、開啓二級緩存
1.二級緩存是mapper範圍級別的,除了在configuration.xml設置二級緩存的總開關,還在在個體的mapper.xml中開啓二級緩存
<settings> <!--開啓延時加載 --> <setting name="lazyLoadingEnabled" value="true"/> <!--關閉當即加載 --> <setting name="aggressiveLazyLoading" value="false"/> <!--開啓二級緩存 --> <setting name="cacheEnabled" value="true" /> </settings>
2.mapper對就的pojo類,實現序列化
3.在authorMapper中開啓二級緩存
<!--開啓本mapper下的二級緩衝 --> <cache />
7.三、測試
@Test public void testCache() { // 獲取會話工廠 SqlSession sqlSession1 = sqlSessionFactory.openSession(); AuthorMapper authorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // 第一次查詢 Author author1 = authorMapper1.findAuthorById(2); //必須關閉不數據沒法寫到緩存區域 sqlSession1.close(); // 獲取會話工廠 /*SqlSession sqlSession2 = sqlSessionFactory.openSession(); AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class); sqlSession2.close();*/ // 獲取會話工廠 SqlSession sqlSession3 = sqlSessionFactory.openSession(); AuthorMapper authorMapper3 = sqlSession3.getMapper(AuthorMapper.class); // 第一次查詢 Author author3 = authorMapper3.findAuthorById(2); sqlSession3.close(); }
DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.0 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 873769339. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Returned connection 873769339 to pool. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.5
中間增長commit操做
@Test public void testCache() { // 獲取會話工廠 SqlSession sqlSession1 = sqlSessionFactory.openSession(); AuthorMapper authorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // 第一次查詢 Author author1 = authorMapper1.findAuthorById(2); //必須關閉不數據沒法寫到緩存區域 sqlSession1.close(); // 獲取會話工廠 SqlSession sqlSession2 = sqlSessionFactory.openSession(); AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class); Author author2 = authorMapper2.findAuthorById(2); //更新 author2.setAuthorUserName("董事長"); author2.setAuthroBio("公司"); authorMapper2.updateAuthor(author2); //commit會清空緩存區域 sqlSession2.commit(); sqlSession2.close(); // 獲取會話工廠 SqlSession sqlSession3 = sqlSessionFactory.openSession(); AuthorMapper authorMapper3 = sqlSession3.getMapper(AuthorMapper.class); // 第一次查詢 Author author3 = authorMapper3.findAuthorById(2); sqlSession3.close(); }
結果:
DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.0 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 873769339. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Returned connection 873769339 to pool. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.5 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Checked out connection 873769339 from pool. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - ==> Preparing: update author SET author_username=?, author_password=?, author_email=?, author_bio=?, register_time=? where author_id=? DEBUG [main] - ==> Parameters: 董事長(String), 123asf(String), lisi@163.com(String), 公司(String), 2015-10-29 10:24:29.0(Timestamp), 2(Integer) DEBUG [main] - <== Updates: 1 DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Returned connection 873769339 to pool. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.3333333333333333 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Checked out connection 873769339 from pool. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b] DEBUG [main] - Returned connection 873769339 to pool.
8.一、把jar包導入項目
8.二、創建ehcache.xml
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="F:\develop\ehcache" /> <defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache>
8.三、在mapper的cache中指定type
<!--開啓本mapper下的二級緩衝 type指定爲ehcachecache類開 在ehcache和mybatis的整合包中 --> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
8.四、測試
@Test public void testCache() { // 獲取會話工廠 SqlSession sqlSession1 = sqlSessionFactory.openSession(); AuthorMapper authorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // 第一次查詢 Author author1 = authorMapper1.findAuthorById(2); //必須關閉不數據沒法寫到緩存區域 sqlSession1.close(); // 獲取會話工廠 SqlSession sqlSession2 = sqlSessionFactory.openSession(); AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class); Author author2 = authorMapper2.findAuthorById(2); //更新 author2.setAuthorUserName("董事長"); author2.setAuthroBio("公司"); authorMapper2.updateAuthor(author2); //commit會清空緩存區域 sqlSession2.commit(); sqlSession2.close(); // 獲取會話工廠 SqlSession sqlSession3 = sqlSessionFactory.openSession(); AuthorMapper authorMapper3 = sqlSession3.getMapper(AuthorMapper.class); // 第一次查詢 Author author3 = authorMapper3.findAuthorById(2); sqlSession3.close(); }
結果:
DEBUG [main] - Configuring ehcache from ehcache.xml found in the classpath: file:/E:/mywork/MybatisDemo2/bin/ehcache.xml DEBUG [main] - Configuring ehcache from URL: file:/E:/mywork/MybatisDemo2/bin/ehcache.xml DEBUG [main] - Configuring ehcache from InputStream DEBUG [main] - Ignoring ehcache attribute xmlns:xsi DEBUG [main] - Ignoring ehcache attribute xsi:noNamespaceSchemaLocation DEBUG [main] - Disk Store Path: F:\develop\ehcache DEBUG [main] - Creating new CacheManager with default config DEBUG [main] - propertiesString is null. DEBUG [main] - No CacheManagerEventListenerFactory class specified. Skipping... DEBUG [main] - No BootstrapCacheLoaderFactory class specified. Skipping... DEBUG [main] - CacheWriter factory not configured. Skipping... DEBUG [main] - No CacheExceptionHandlerFactory class specified. Skipping... DEBUG [main] - Initialized net.sf.ehcache.store.NotifyingMemoryStore for com.pb.mybatis.mapper.AuthorMapper DEBUG [main] - Initialised cache: com.pb.mybatis.mapper.AuthorMapper DEBUG [main] - CacheDecoratorFactory not configured for defaultCache. Skipping for 'com.pb.mybatis.mapper.AuthorMapper'. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.0 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 1286943672. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Returned connection 1286943672 to pool. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.5 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Checked out connection 1286943672 from pool. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - ==> Preparing: update author SET author_username=?, author_password=?, author_email=?, author_bio=?, register_time=? where author_id=? DEBUG [main] - ==> Parameters: 董事長(String), 123asf(String), lisi@163.com(String), 公司(String), 2015-10-29 10:24:29.0(Timestamp), 2(Integer) DEBUG [main] - <== Updates: 1 DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Returned connection 1286943672 to pool. DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.3333333333333333 DEBUG [main] - Opening JDBC Connection DEBUG [main] - Checked out connection 1286943672 from pool. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8] DEBUG [main] - Returned connection 1286943672 to pool.