Home >Java >javaTutorial >Getting Started with MyBatis (5) --- Delayed loading and caching
1. Create database
1.1. Create database
/*SQLyog EnterPRise v12.09 (64 bit)MySQL - 5.7.9-log : Database - mybatis
**********************************************************************//*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `mybatis`;/*Table structure for table `author` */DROP TABLE IF EXISTS `author`;CREATE TABLE `author` (
`author_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '作者ID主键',
`author_username` varchar(30) NOT NULL COMMENT '作者用户名',
`author_passWord` varchar(32) NOT NULL 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_INCREMENT=11 DEFAULT CHARSET=utf8;/*Data for the table `author` */insert into `author`(`author_id`,`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,'张无忌','qwertyuiop','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');/*Table structure for table `blog` */DROP TABLE IF EXISTS `blog`;CREATE TABLE `blog` (
`blog_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'BlogId主键',
`blog_title` varchar(255) NOT NULL COMMENT 'blog标题',
`author_id` int(11) unsigned NOT NULL COMMENT '作者ID外键', PRIMARY KEY (`blog_id`), KEY `fk_author_id` (`author_id`), CONSTRAINT `fk_author_id` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;/*Data for the table `blog` */insert into `blog`(`blog_id`,`blog_title`,`author_id`) values (1,'小张的Blog',1),(2,'小李',2),(3,'王五不是人',3),(4,'赵地人',4),(5,'钱钱钱',5);/*Table structure for table `posts` */DROP TABLE IF EXISTS `posts`;CREATE TABLE `posts` (
`post_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '文章主键ID',
`post_subject` varchar(255) NOT NULL COMMENT '文章主题,标题',
`post_body` text NOT NULL COMMENT '文章内容最大3000个字符',
`blog_id` int(11) unsigned NOT NULL COMMENT 'Blog主键做外键',
`createtime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '文章创建时间', PRIMARY KEY (`post_id`), KEY `fk_blog_id` (`blog_id`), CONSTRAINT `fk_blog_id` FOREIGN KEY (`blog_id`) REFERENCES `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`) values (1, 'Introduction to Mybatis 1', 'What is MyBatis? rnMyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. MyBatis can use simple xml or annotations for configuration and native Maps to map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database. ',1,'2015-10-29 10: 32:21'),(2,'Introduction to Mybatis 2','To use MyBatis, just place the mybatis-x.x.x.jar file in the classpath.',1,'2015-10-29 10:32:52 '),(3,'Oracle Learning','Oracle Database, also known as Oracle RDBMS, or Oracle for short. It is a relational database management system of Oracle Company',2,'2015-10-29 10:33:26' ),(4,'JAVA Learning 1','Java is the general name of the Java object-oriented programming language and Java platform launched by Sun Microsystems in May 1995',3,'2015-10-29 10:34: 17'),(5,'PL/SQL','PL/SQL is also a programming language called Procedural Language/SQL. PL/SQL is an extension of Oracle database to SQL statements',4, '2015-10-29 10:37:52'),(6,'CSS tag selector','Tag selectorrnID selectorrnClass selectorrnSpecial selector',5,'2015-10-29 10 :39:44'),(7,'javascript','js: is a front-end scripting language',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 */;/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Data tables and data
2. Create a project
2.1. Create a project
3. Establish entity classes and Mapper interfaces
3.1. 3 entity classes
package com.pb.mybatis.po; import java .util.Date;/**
*
* @ClassName: Author
* @Description: TODO(author)
* @author Liu Nan
* @date 2015-10-31 12:39:33 pm
**/public class Author { //Author ID
private Integer authorId; //Author name
private String authorUserName; //Author password
private String authorPassword; //Author email
private String authorEmail; //Author introduction
private String authroBio; //Registration time
private Date registerTime;
public Integer getAuthorId() { return authorId;
} } public void set AuthorId(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="
;
}
}
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
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
} public void setPostsList(List
}
@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.2、3个接口
package com.pb.mybatis.mapper;import com.pb.mybatis.po.Author;public interface AuthorMapper { /**
* *
* @Title: findAuthorById
* @Description: TODO (search based on id)
* @param @param id
* @param @return Setting file
* @return Author Return type
* @ throws
*/
public Author findAuthorById(int id);
}
package com.pb.mybatis.mapper;import com.pb.mybatis.po.Blog;public interface BlogMapper {
/**
*
* @Title: findBlogById
* @Description: TODO (Find BLOG based on BLOGID, associate author, and implement delayed loading with posts)
* @param @param id
* @param @return Setting file
* @return Blog Return type
* @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 (find post list based on BLOGID)
* @param @param blogId
* @param @return Setting file
* @return List
* @throws
*/
public List
}
四、建立mapper.xml与confinguration.xml
4.1、相对应的mapper.xml
AuthorMapper.xml
br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
BlogMapper.xml
br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis .org/dtd/mybatis-3-mapper.dtd">
PostsMapper.xml
br/> PUBLIC "-// mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
4.2, configuration.xml
db.properties
driver=com.mysql.jdbc .Driver
url=jdbc:mysql://localhost:3306/mybatis?character=utf8
username=root
password=root
Enable delayed loading and turn off immediate loading
br/> PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis .org/dtd/mybatis-3-config.dtd">
5. Test
5. 1. 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 (delayed loading)
* @param Setting file
* @return void Return type
* @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
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] - 1...小张的Blog===========开始延时加载作者Author===========DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - Preparing: select * from posts where blog_id=? DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] -
六、一级缓存
6.1、mybatis一级缓存
mybatis,默认开启了一级缓存,sqlSession中默认有一个hashMap
当查询时,先去hashMap中查找,
如果有就直接,取出,不再操作数据库
如果没有就去数据库查找,并放在haspMap中
当做事物时,如添加,删除,修改,后有commit时会清空一级缓存
sqlSession是互不影响的,一级缓存
6.2、还是上级的例子
测试:查询用户
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] - 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] -
6.3、当查询后,做事务,再查询第一次的
接口中做添加方法
/**
* *
* @Title: addAuthor
* @Description: TODO(Add)
* @param @param author
* @param @return Setting file
* @return int Return type
* @throws
*/
public int addAuthor(Author author);
mapper.xml中做同样的select
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})
测试
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] - 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] - DEBUG [main] - ==> Preparing: select * from author where author_id=? DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] -
七、二级缓存
7.1、mybatis二级缓存与一级缓存
sqlSession是互不影响的,一级缓存
Mapper(namespace)是二级缓存
多个sqlSession可以共享一个Mapper的二级缓存区域
二级缓存按namespace分,其它的mapper也有自己的二级缓存区域namespace
第一个namespace的mapper都有一个二级缓存区域,2个mapper的namespace如果相同,这2个mapper执行sql查询数据将存在相同的二级缓存区域中.
7.2、开启二级缓存
1.二级缓存是mapper范围级别的,除了在configuration.xml设置二级缓存的总开关,还在在个体的mapper.xml中开启二级缓存
2. The pojo class matched by the mapper implements serialization
3. Enable the second-level cache in the authorMapper
AuthorMapper authorMapper1 = sqlSession1.getMapper (AuthorMapper.class); // First query
AuthorMapper2 = sqlSession2.getMapper(AuthorMapper.class);
sqlSession2.close();*/// Get the session factory
SqlSe ssion sqlSession3 = sqlSessionFactory.openSession();AuthorMapper authorMapper3 = sqlSession3 .getMapper(AuthorMapper.class); // First query
Author author3 = authorMapper3.findAuthorById(2);sqlSession3.close();
}
DEBUG [main] - Cache Hit Ratio [com. pb.mybatis.mapper.AuthorMapper]: 0.0DEBUG [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] - 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
SqlSe ssion sqlSession1 = sqlSessionFactory.openSession();
AuthorMapper authorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // First query
AuthorMapper1.findAuthorById(2); //Must be closed because data cannot be written to the cache area sqlSession1 .close(); // Get the session factory
SqlSession sqlSession2 = sqlSessionFactory.openSession(); AuthorMapper authorMapper2 = sqlSession2.getMapper(AuthorMapper.class);
Auth or author2 = authorMapper2.findAuthorById(2); //Update
author2. setAuthorUserName("Chairman");
author2.setAuthroBio("Company");
authorMapper2.updateAuthor(author2); //commit will clear the cache area sqlSession2.commit();
sqlSession2 .close(); // Get session Factory
AuthorMapper authorMapper3 = sqlSession3.getMapper(AuthorMapper.class); sqlSession3 = using using using using sqlSession ‐ ‐ Mapper3.findAuthorById(2);
sqlSession3.close(); }
Result:
DEBUG [main] - Cache Hit Ratio [com.pb.mybatis.mapper.AuthorMapper]: 0.0DEBUG [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] - 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.5DEBUG [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] - 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.3333333333333333DEBUG [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] - DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3414a97b]
DEBUG [main] - Returned connection 873769339 to pool.
八、Mybatis与ehcache整合
8.1、把jar包导入项目
8.2、建立ehcache.xml
ehcache.xml
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
8.3、在mapper的cache中指定type
8.4、测试
@Test public void testCache() { // Get the session factory
SqlSession sqlSession1 = sqlSessionFactory.openSession();
AuthorMapper1 = sqlSession1.getMapper(AuthorMapper.class); // First query
Author author1 = authorMapper1.findAuthorById (2); //Must be closed because no data can be written to the cache area. sqlSession1.close(); sqlSession2.getMapper(AuthorMapper.class);
Author author2 = authorMapper2.findAuthorById(2); //Update
author2.setAuthorUserName("Chairman");
author2.setAuthroBio("Company");
authorMapper2.updateAuthor(author2); // Commit will clear the cache area sqlSession2 .commit();
sqlSession2.close(); use using using using ’ sqlSession ’ sqlSession ’ sqlSession 3 = sqlSession 3. pper(AuthorMapper.class); // First query
Author author3 = authorMapper3.findAuthorById(2);
sqlSession3.close();
}
Result:
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:developehcache
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.0DEBUG [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] - 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.5DEBUG [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] - 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.3333333333333333DEBUG [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] - DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4cb533b8]
DEBUG [main] - Returned connection 1286943672 to pool.
以上就是MyBatis入门(五)---延时加载、缓存的内容,更多相关内容请关注PHP中文网(www.php.cn)!