Mybatis 的使用 (7) 缓存

1. 缓存

1.1     一级缓存

l  Mybatis一级缓存默认存在的,不需要配置

l  一级缓存的生命周期为Session的生命周期,如果session关闭,一级缓存消失

l  一级缓存,存储的是对象的地址

1.2     二级缓存

第一步:在sqlMapConfig.xml中开启二级缓存功能

<settings>
	<setting name="cacheEnabled" value="true" />
</settings>

第二步:在sql映射文件中使用<cache/>标签,指定当前文件中的sql语句可以使用缓存数据,也可以修改默认参数:

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

第三步:在<select>标签中使用useCache指定当前sql语句是否使用缓存数据

1.3 Ehcache缓存

第一步:导入Ehcache相关jar包

<dependency>
	<groupId>org.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
	<groupId>org.mybatis.caches</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.1.0</version>
	<exclusions>
		<exclusion>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</exclusion>
	</exclusions>
</dependency>

第二步:在项目的类路径下提供Ehcache的核心配置文件ehcache.xml,可以从Ehcache的核心jar包中获得

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

	<diskStore path="java.io.tmpdir" />

	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000"
		diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
		<persistence strategy="localTempSwap" />
	</defaultCache>
</ehcache>

第三步:修改sql映射文件中的<cache>标签

<cache type="org.mybatis.caches.ehcache.EhcacheCache" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值