目录
十六、mybatis缓存
- 缓存:
1、缓存是指把经常需要读取的数据保存到一个高速的缓冲区中,这个行为叫缓存。
2、缓存也可以是指被保存到高速缓冲区中的数据,也叫缓存。
一级缓存: 是指把数据保存到SqlSession中
二级缓存: 是指把数据保存到SqlSessionFactory中
1、mybatis的一级缓存的示例
User对象
public class User {
private Integer id;
private String lastName;
private Integer sex;
UserMapper接口
public interface UserMapper {
public User queryUserById(Integer id);
}
UserMapper.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.atguigu.mapper.UserMapper">
<!-- public User queryUserById(Integer id); -->
<select id="queryUserById" resultType="com.atguigu.pojo.User">
select id,last_name lastName,sex from t_user where id = #{id}
</select>
</mapper>
测试代码:
public class UserMapperTest {
@Test
public void testQueryUserById() throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper userMapper = session.getMapper(UserMapper.class);
System.out.println( userMapper.queryUserById(1) );
System.out.println( userMapper.queryUserById(1) );
System.out.println( userMapper.queryUserById(1) );
System.out.println( userMapper.queryUserById(1) );
System.out.println( userMapper.queryUserById(1) );
} finally {
session.close();
}
}
}
1.2、一级缓存的管理
缓存失效的四种情况:
- 不在同一个SqlSession对象中
public void queryOne() {
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println( mapper.queryUserById(1) );
} finally {
session.close();
}
}
@Test
public void testCacheFail1() throws IOException {
// 1.不在同一个SqlSession对象中
queryOne();
queryOne();
}
2.执行语句的参数不同。缓存中也不存在数据
@Test
public void testCacheFail2() throws IOException {
// 2.执行语句的参数不同。缓存中也不存在数据。
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println( mapper.queryUserById(1) );
System.out.println( mapper.queryUserById(5) );
} finally {
session.close();
}
}
- 执行增,删,改,语句,会清空掉缓存
@Test
public void testCacheFail3() throws IOException {
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.queryUserById(1));
// 3.执行增,删,改,语句,会清空掉缓存
mapper.updateUser(new User(2,"cc",1));
System.out.println(mapper.queryUserById(1));
} finally {
session.close();
}
}
- 手动清空缓存数据
@Test
public void testCacheFail4() throws IOException {
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.queryUserById(1));
// 4.手动清空缓存数据
session.clearCache();
System.out.println(mapper.queryUserById(1));
} finally {
session.close();
}
}
2、mybatis的二级缓存
二级缓存的图解示意
二级缓存的使用:
myBatis的二级缓存默认是不开启的。
1、我们需要在mybatis的核心配置文件中配置setting选项
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
2、在Mapper的配置文件中加入cache标签。
<!-- 仅仅加入这个 标签就可以了 -->
<cache>
</cache>
<!-- useCache 默认true
-->
<select id="queryUserById" resultType="com.atguigu.bean.User" useCache="true">
select id,last_name lastName,sex from t_user where id = #{id}
</select>
3、并且需要被二级缓存的对象必须要实现java的序列化接口。
public class User implements Serializable{}
2.1、二级缓存的演示
public void queryOne() {
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.queryUserById(1));
} finally {
session.close();
}
}
@Test
public void testSecondCache() throws IOException {
queryOne();
queryOne();
queryOne();
queryOne();
}
2.2、useCache="false"的演示和说明
在select标签中,useCache属性表示是否使用二缓存。默认是true,表示使用二级缓存(每次查询完之后。也会把这个查询的数据,放到二级缓存中)
<select id="queryUserById" resultType="com.atguigu.pojo.User" useCache="true">
select id,last_name lastName,sex from t_user where id = #{id}
</select>
2.3、flushCache="false"的演示和说明
在insert、delete、update标签中,都有flushCache属性,这个属性决定着执行完增,删,改的语句之后要不要清空二级缓存。
默认值都是true。
<!-- public int updateUser(User user); -->
<update id="updateUser" parameterType="com.atguigu.pojo.User" flushCache="false">
update t_user set last_name = #{lastName},sex=#{sex} where id = #{id}
</update>
2.4、标签的介绍和说明
默认的标签的作用:
1、映射语句文件中的所有 select 语句将会被缓存。
2、射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。
3、缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。
4、根据时间表(比如 no Flush Interval,没有刷新间隔), 缓存不会以任何时间顺序 来刷新。
5、缓存会存储列表集合或对象(无论查询方法返回什么)的 1024 个引用。
6、缓存会被视为是 read/write(可读/可写)的缓存,意味着对象检索不是共享的,而 且可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
cache标签示例解析:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
- eviction 属性表示缓存策略。
LRU – 最近最少使用的:移除最长时间不被使用的对象(这是默认策略)。
FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
- flushInterval 属性表示间隔多长时间刷新一下缓冲区,清理一下溢出的数据。以毫秒为单位。
- size 属性表示缓存中可以保存多少个对象。默认是1024。
- readOnly 属性表示是否只读。如果设置为true。表示缓存中只有一个对象。如果设置为false(默认为false)每次取出来都会反序列化拷贝一份。
- type 属性表示自定义二级缓存对象。
缓存的使用顺序说明
1、当我们执行一个查询语句的时候。mybatis会先去二级缓存中查询数据。如果二级缓存中没有。就到一级缓存中查找。
2、如果二级缓存和一级缓存都没有。就发sql语句到数据库中去查询。
3、查询出来之后马上把数据保存到一级缓存中。
4、当SqlSession关闭的时候,会把一级缓存中的数据保存到二级缓存中
十八、Batista 逆向工程
MyBatis逆向工程,简称MBG。是一个专门为MyBatis框架使用者定制的代码生成器。可以快速的根据表生成对应的映射文件,接口,以及Bean类对象。
在Mybatis中,有一个可以自动对单表生成的增,删,改,查代码的插件。
叫 mybatis-generator-core-1.3.2。
它可以帮我们对比数据库表之后,生成大量的这个基础代码。
这些基础代码有:
1、数据库表对应的javaBean对象
2、这些javaBean对象对应的Mapper接口
3、这些Mapper接口对应的配置文件
<!-- 去掉全部的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
1、准备数据库表
create database mbg;
use mbg;
create table t_user(
`id` int primary key auto_increment,
`username` varchar(30) not null unique,
`password` varchar(40) not null,
`email` varchar(50)
);
insert into t_user(`username`,`password`,`email`) values('admin','admin','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('wzg168','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('admin168','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('lisi','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('wangwu','123456','admin@atguigu.com');
create table t_book(
`id` int primary key auto_increment,
`name` varchar(50),
`author` varchar(50),
`price` decimal(11,2),
`sales` int,
`stock` int
);
## 插入初始化测试数据
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , 'java从入门到放弃' , '国哥' , 80 , 9999 , 9);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '数据结构与算法' , '严敏君' , 78.5 , 6 , 13);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '怎样拐跑别人的媳妇' , '龙伍' , 68, 99999 , 52);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '木虚肉盖饭' , '小胖' , 16, 1000 , 50);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , 'C++编程思想' , '刚哥' , 45.5 , 14 , 95);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '蛋炒饭' , '周星星' , 9.9, 12 , 53);
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '赌神' , '龙伍' , 66.5, 125 , 535);
select * from t_user;
select * from t_book;
1、创建一个Java工程
2、导入jar包
log4j-1.2.17.jar
mybatis-3.4.1.jar
mybatis-generator-core-1.3.2.jar
mysql-connector-java-5.1.7-bin.jar
3、准备配置文件:
mbg.xml 逆向工程的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
targetRuntime 表示你要生成的版本
MyBatis3 豪华版本
MyBatis3Simple CRUD标准版
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!-- 去掉全部的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mbg"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator配置生成模型JavaBean
targetPackage生成的javaBean的包名
targetProject生成之后在哪个工程目录下
-->
<javaModelGenerator targetPackage="com.atguigu.pojo" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--
sqlMapGenerator生成sql的mapper.xml配置文件
targetPackage生成mapper.xml配置文件放的包名
-->
<sqlMapGenerator targetPackage="com.atguigu.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--
javaClientGenerator配置生成的Mapper接口
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 一个table标签,表示一个表 -->
<table tableName="t_user" domainObjectName="User" ></table>
<table tableName="t_book" domainObjectName="Book" ></table>
</context>
</generatorConfiguration>
log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis-config.xml
<?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>
<settings>
<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 将积极加载改为消极加载 按需加载 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mbg" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 通过指定包的方式扫描接口和mapper.xml配置文件 -->
<package name="com.atguigu.mapper" />
</mappers>
</configuration>
生成mbyatis的代码(每次生成都要先把原来的给删了):
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class Runner {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
}