一、MyBatis的Cache配置
1、全局开关:默认是true,如果它配成false,其余各个Mapper XML文件配成支持cache也没用。
<settings>
<setting name="cacheEnabled" value="true"/>
本文摘自 Mybatis入门实例(二)——添加ehcache缓存支持
1、全局开关:默认是true,如果它配成false,其余各个Mapper XML文件配成支持cache也没用。
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
架包:
1.ehcache-core-2.4.4.jar
2.mybatis-ehcache-1.0.0.jar
3.slf4j-api-1.6.1.jar
4.slf4j-log4j12-1.6.2.jar
5.log4j.jar
二、配置ehcache.xml(好像必须已这个命名,也必须放在根目录下),
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../bin/ehcache.xsd">
<!--
name:Cache的唯一标识
maxElementsInMemory:内存中最大缓存对象数
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
eternal:Element是否永久有效,一但设置了,timeout将不起作用
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大
diskPersistent:是否缓存虚拟机重启期数据
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
备注: 持久化到硬盘的路径由虚拟机参数"java.io.tmpdir"决定.
例如, 在windows中, 会在此路径下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常会在: /tmp 下
System.out.println(System.getProperty("java.io.tmpdir"));
-->
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="0" eternal="false"
timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" />
</ehcache>
然后需要在sqlMapper中配置<cache> 标签
<?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" >
<!-- namespace用于java代码调用时识别指定xml的mapper文件 -->
<mapper namespace="com.yeshun.bean.UserInfo">
<!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
<!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->
<!-- 配置ORM映射 -->
<resultMap type="UserInfo" id="BaseResultMap" >
<id property="userid" column="user_id" jdbcType="VARCHAR"/>
<result property="username" column="user_name" jdbcType="VARCHAR"/>
<result property="password" column="password" jdbcType="VARCHAR"/>
</resultMap>
<!-- 用来定义可重用的SQL代码段 -->
<sql id="demo_sql">
userid,username,password
</sql>
<insert id="inser_userInfo" parameterType="UserInfo">
<!-- include 引用可重用的SQL代码段 -->
INSERT INTO user_table(<include refid="demo_sql"/>) VALUES(#{userid},#{username},#{password})
</insert>
<select id="selectAll_userInfo" useCache="false" flushCache="true" resultMap="BaseResultMap">
SELECT * FROM user_table
</select>
<select id="selectById_userInfo" parameterType="String" resultType="UserInfo">
SELECT * FROM user_table WHERE id= #{id}
</select>
</mapper>
本文摘自 Mybatis入门实例(二)——添加ehcache缓存支持