一、创建数据库

1.1、建立数据库

/*
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,'张三','','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,'张三丰','','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,'Mybatis入门一','什么是 MyBatis ?\r\nMyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。',1,'2015-10-29 10: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标签选择器','标签选择器\r\nID选择器\r\n类选择器\r\n特殊选择器',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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

数据表和数据

二、创建项目

2.1、创建项目

三、建立实体类与Mapper接口

3.1、3个实体类

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.2、3个接口

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);
}

四、建立mapper.xml与confinguration.xml

4.1、相对应的mapper.xml

AuthorMapper.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.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

<?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.2、configuration.xml

db.properties

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.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(延时加载) * @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.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] - <== 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.3、当查询后,做事务,再查询第一次的

接口中做添加方法

/**
* * @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.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中开启二级缓存

<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.3、测试

@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.

八、Mybatis与ehcache整合

8.1、把jar包导入项目

8.2、建立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.3、在mapper的cache中指定type

<!--开启本mapper下的二级缓冲
type指定为ehcachecache类开
在ehcache和mybatis的整合包中
-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

8.4、测试

@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.

MyBatis入门(五)---延时加载、缓存的更多相关文章

  1. Mybatis 中延时加载

    1 为了处理N+1 问题,Mybatis 引入了延时加载功能,意义是一开始并不取出关联数据,只有当使用时,才发送sql语句去取. mybatis中两个全局设置 lazyLoadingEnabled 和 ...

  2. MyBatis中二级缓存和延时加载同时开启的问题

    首先,二级缓存默认不开启! 要配置 <setting name="cacheEnabled" value="true"/> 在MyBatis中:一级 ...

  3. FreeSql (二十五)延时加载

    FreeSql 支持导航属性延时加载,即当我们需要用到的时候才进行加载(读取),支持1对1.多对1.1对多.多对多关系的导航属性. 当我们希望浏览某条订单信息的时候,才显示其对应的订单详细记录时,我们 ...

  4. webpack入坑之旅(五)加载vue单文件组件

    这是一系列文章,此系列所有的练习都存在了我的github仓库中vue-webpack,在本人有了新的理解与认识之后,会对文章有不定时的更正与更新.下面是目前完成的列表: webpack入坑之旅(一)不 ...

  5. mybatis_12延时加载_懒加载

    延时加载:也叫懒加载 2.1 延迟加载 延迟加载又叫懒加载,也叫按需加载.也就是说先加载主信息,在需要的时候,再去加载从信息. 在mybatis中,resultMap标签 的association标签 ...

  6. 图片延时加载原理 和 使用jquery实现的一个图片延迟加载插件(含图片延迟加载原理)

    图片加载技术分为:图片预加载和图片延时加载. javascript图片预加载和延时加载的区别主要体现在图片传输到客户端的时机上,都是为了提升用户体验的,延时加载又叫懒加载.两种技术的本质:两者的行为是 ...

  7. 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理

    服务器文档下载zip格式   刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...

  8. javascript脚本的延时加载

    javascript脚本的延时加载 向HTML页面中插入js代码的主要方法是使用<script>标签,在实际的开发中多采用外部文件的方式,主要考虑到外部js代码的可维护性及可缓存性等优点. ...

  9. 《Entity Framework 6 Recipes》中文翻译系列 (22) -----第五章 加载实体和导航属性之延迟加载

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第五章 加载实体和导航属性 实体框架提供了非常棒的建模环境,它允许开发人员可视化地使 ...

随机推荐

  1. MyBatis 元素类型为 "configuration" 的内容必须匹配 ".....

    修改MyBatis配置文件时,添加typeAliases节点,报了一个BuilderException: org.apache.ibatis.exceptions.PersistenceExcepti ...

  2. 解决 -ERR Plaintext authentication disallowed on non-secure (SSL/TLS) connections 方案[sendmail, dovecot]

    在linux下安装sendmail比较容易, 但是在配置sendmail时却是比较麻烦的, 特别是对于一些新手来说, 配置过程必须十分小心谨慎, 要知道, 错误是千奇百怪, 但是成功的结果就只有一个, ...

  3. 编写高质量JS代码的68个有效方法(五)

    No.21.使用apply方法通过不同数量的参数调用函数 Tips: 使用apply方法自定一个可计算的参数数组来调用可变参数的函数 使用apply方法的第一个参数给可变参数的方法提供一个接收者 // ...

  4. JS&CSS文件请求合并及压缩处理研究(二)

    上篇交待了一些理论方面的东西,并给出了另外一种解决方案的处理流程.本篇将根据该处理流程,开始代码方面的编写工作. 1,打开VS,新建ASP.NET MVC Web项目,项目类型选择空.名称为 Mcmu ...

  5. Hekaton是如何影响你数据库的目标恢复时间(RTO)的

    这个周末我发现了SQL Server 2014里Hekaton的一个有趣副作用,很遗憾它会负面影响你数据库的目标恢复时间(Recovery Time Objective,RTO).你已知道,对于每个本 ...

  6. Velocity魔法堂系列二:VTL语法详解

    一.前言 Velocity作为历史悠久的模板引擎不单单可以替代JSP作为Java Web的服务端网页模板引擎,而且可以作为普通文本的模板引擎来增强服务端程序文本处理能力.而且Velocity被移植到不 ...

  7. [新手学Java]使用内省(Introspector)操作JavaBean属性

    获取类bean中的所有属性: @Test //获取类bean中的所有属性 public void test1() throws Exception{ BeanInfo info = Introspec ...

  8. 002_Razor简介

    关于 Razor: Razor 语句以 @ 字符开始.在使用 Razor 声明视图模型对象的类型时要使用小写字母,如在本例文件 Index.cshtml 文件中 @model 以小写的 m 开头,但要 ...

  9. n个人作m幅画

    题目网址: http://codeforces.com/problemset/problem/416/B A well-known art union called "Kalevich is ...

  10. Python 学习之进制与编码

    进制 日常生活中,我们最熟悉的数据就是十进制计数.它的数值部分由十个不同的数字符号0.1.2.3.4.5.6.7.8.9来表示,我们把这些数字符号叫做数码,表示十种不同的状态.数码处于不同的位置(或数 ...