在java程序运行过程中,每次调用都会访问数据库吗?答案是否定的,java会有缓存将访问过的存起来下次调用时就不在连接数据库了,而是从缓存中找。
mybatis缓存详细:http://blog.csdn.net/marvel__dead/article/details/70133715 引用别人的,写的挺好
下面是我自己的测试:
一.配置文件的写法
log4 相关包是为了测试用的,主要在控制台显示程序的进程。ehcache 和 mybatis-ehcache是俩个mybatis的缓存包,外部缓存需要添加的jar包
步骤如下:
1.配置文件: conf.xml usermapper.xml
2. conf.xml 第四行的setting标签,启用缓存(外部缓存和二级缓存都需要)
<?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="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/luntan" />
<property name="username" value="root" />
<property name="password" value="mysql" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="it/com/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.缓存只有select有,所以那条select使用缓存,记得在标签里将 userCache改成true
同时配置cache标签,下面代码使用的是外部缓存,被注释的是二级缓存,里面的配置标签property ehcache.xml文件中有,外部缓存会jar包会自动调用
<?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="it.com.dao">
<!-- 缓存配置 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache">
<!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"> -->
<property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
<property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
<property name="maxEntriesLocalHeap" value="10000"/>
<property name="maxEntriesLocalDisk" value="10000000"/>
</cache>
<select id="findall" resultType="Map" useCache="true"><!-- 使用缓存 -->
select * from users
</select>
<select id="findById" resultType="Map" parameterType="String" useCache="true">
select * from users where userName = #{userName}
</select>
<select id="findByIdPwd" resultType="Map" parameterType="Map">
select * from users where userName = #{userName} and userPwd=#{userPwd}
</select>
<insert id="insertByIdPwd" parameterType="Map">
insert into users(userName,userPwd) values (#{userName},#{userPwd})
</insert>
</mapper>
4.在userDao中调用方法
public List<Map> findById(String userName){
List<Map> list=null;
SqlSession session = SF.getSession();
list=session.selectList("findById",userName);
session.commit();//使用缓存必须写
return list;
}
测试结果:
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Configuring ehcache from ehcache.xml found in the classpath: file:/F:/myeclipse%20%20workspace/test08021/WebRoot/WEB-INF/classes/ehcache.xml
DEBUG - Configuring ehcache from URL: file:/F:/myeclipse%20%20workspace/test08021/WebRoot/WEB-INF/classes/ehcache.xml
DEBUG - Configuring ehcache from InputStream
DEBUG - Disk Store Path: F:\ehcache111
DEBUG - Creating new CacheManager with default config
DEBUG - propertiesString is null.
DEBUG - No CacheManagerEventListenerFactory class specified. Skipping...
DEBUG - No BootstrapCacheLoaderFactory class specified. Skipping...
DEBUG - CacheWriter factory not configured. Skipping...
DEBUG - No CacheExceptionHandlerFactory class specified. Skipping...
DEBUG - Initialized net.sf.ehcache.store.MemoryStore for it.com.dao
WARN - diskStorePath 'F:\ehcache111' is already used by an existing CacheManager either in the same VM or in a different process.
The diskStore path for this CacheManager will be set to F:\ehcache111\ehcache_auto_created7300060912575425752diskstore.
To avoid this warning consider using the CacheManager factory methods to create a singleton CacheManager or specifying a separate ehcache configuration (ehcache.xml) for each CacheManager instance.
DEBUG - Using diskstore path F:\ehcache111\ehcache_auto_created7300060912575425752diskstore
DEBUG - Holding exclusive lock on F:\ehcache111\ehcache_auto_created7300060912575425752diskstore\.ehcache-diskstore.lock
DEBUG - Failed to delete file it%002ecom%002edao.data
DEBUG - Failed to delete file it%002ecom%002edao.index
DEBUG - Matching data file missing (or empty) for index file. Deleting index file F:\ehcache111\ehcache_auto_created7300060912575425752diskstore\it%002ecom%002edao.index
DEBUG - Failed to delete file it%002ecom%002edao.index
DEBUG - Initialised cache: it.com.dao
DEBUG - CacheDecoratorFactory not configured for defaultCache. Skipping for 'it.com.dao'.
DEBUG - Cache Hit Ratio [it.com.dao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1763371495.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@691ae9e7]
DEBUG - ooo Using Connection [com.mysql.jdbc.Connection@691ae9e7]
DEBUG - ==> Preparing: select * from users where userName = ?
DEBUG - ==> Parameters: admire(String)
TRACE - <== Columns: userName, userPwd, Ename, Email, Logo, userId
TRACE - <== Row: admire, 111111, 1111, 11111, 12, 1
DEBUG - <== Total: 1
DEBUG - put added 0 on heap
[{Email=11111, Ename=1111, Logo=12, userId=1, userPwd=111111, userName=admire}]
DEBUG - fault removed 0 from heap
DEBUG - fault added 0 on disk
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
[{Email=11111, Ename=1111, Logo=12, userId=1, userPwd=111111, userName=admire}]
DEBUG - Cache Hit Ratio [it.com.dao]: 1.0
DEBUG - remove deleted 0 from heap
DEBUG - remove deleted 0 from disk
二.注解的写法
注解的写法就相对简单了,只需要在接口文件中
package it.com.db;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.cache.decorators.LruCache;
//配置缓存
@CacheNamespace(size=100,eviction=LruCache.class,implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
public interface IUsersMapper {
//打开缓存
@Options(useCache=true)
@Select("select * from users")
public List<Map> findAll();
@Select("select count(1) from users where userName=#{userName}")
public int findById(@Param("userName") String userName);
//存储过程
@Select("call pp11()")
public List<Map> findAll_a();
}
测试结果:
public int findById(String userName){
SqlSession session = SF.getSession();
IUsersMapper um = session.getMapper(IUsersMapper.class);
int n = um.findById(userName);
session.commit();
return n;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
UsersDao user = new UsersDao();
System.out.println(user.findById("admire"));
System.out.println(user.findById("admire"));
}
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Configuring ehcache from ehcache.xml found in the classpath: file:/F:/myeclipse%20%20workspace/test08021/WebRoot/WEB-INF/classes/ehcache.xml
DEBUG - Configuring ehcache from URL: file:/F:/myeclipse%20%20workspace/test08021/WebRoot/WEB-INF/classes/ehcache.xml
DEBUG - Configuring ehcache from InputStream
DEBUG - Disk Store Path: F:\ehcache111
DEBUG - Creating new CacheManager with default config
DEBUG - propertiesString is null.
DEBUG - No CacheManagerEventListenerFactory class specified. Skipping...
DEBUG - No BootstrapCacheLoaderFactory class specified. Skipping...
DEBUG - CacheWriter factory not configured. Skipping...
DEBUG - No CacheExceptionHandlerFactory class specified. Skipping...
DEBUG - Initialized net.sf.ehcache.store.MemoryStore for it.com.dao
WARN - diskStorePath 'F:\ehcache111' is already used by an existing CacheManager either in the same VM or in a different process.
The diskStore path for this CacheManager will be set to F:\ehcache111\ehcache_auto_created7300060912575425752diskstore.
To avoid this warning consider using the CacheManager factory methods to create a singleton CacheManager or specifying a separate ehcache configuration (ehcache.xml) for each CacheManager instance.
DEBUG - Using diskstore path F:\ehcache111\ehcache_auto_created7300060912575425752diskstore
DEBUG - Holding exclusive lock on F:\ehcache111\ehcache_auto_created7300060912575425752diskstore\.ehcache-diskstore.lock
DEBUG - Failed to delete file it%002ecom%002edao.data
DEBUG - Failed to delete file it%002ecom%002edao.index
DEBUG - Matching data file missing (or empty) for index file. Deleting index file F:\ehcache111\ehcache_auto_created7300060912575425752diskstore\it%002ecom%002edao.index
DEBUG - Failed to delete file it%002ecom%002edao.index
DEBUG - Initialised cache: it.com.dao
DEBUG - CacheDecoratorFactory not configured for defaultCache. Skipping for 'it.com.dao'.
DEBUG - Cache Hit Ratio [it.com.dao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1763371495.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@691ae9e7]
DEBUG - ooo Using Connection [com.mysql.jdbc.Connection@691ae9e7]
DEBUG - ==> Preparing: select * from users where userName = ?
DEBUG - ==> Parameters: admire(String)
TRACE - <== Columns: userName, userPwd, Ename, Email, Logo, userId
TRACE - <== Row: admire, 111111, 1111, 11111, 12, 1
DEBUG - <== Total: 1
DEBUG - put added 0 on heap
[{Email=11111, Ename=1111, Logo=12, userId=1, userPwd=111111, userName=admire}]
DEBUG - fault removed 0 from heap
DEBUG - fault added 0 on disk
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
[{Email=11111, Ename=1111, Logo=12, userId=1, userPwd=111111, userName=admire}]
DEBUG - Cache Hit Ratio [it.com.dao]: 1.0
DEBUG - remove deleted 0 from heap
DEBUG - remove deleted 0 from disk