MyBatis缓存

一:MyBatis的一级缓存默认是开启的,但是如果MyBatis和Spring搭配后,一级缓存失效,如果想用一级缓存,加上@Transactional就可以了。




二:二级缓存:


        在mybatis.xml中加入  在PersonDao.xml中加入





	
		
	
	
		
	





	

	
		
		
	

	
		update person set
		name=#{name} where id=#{id}
	
	


三:可以通过对比日志查看到缓存是否成功。如果不加和加则是以下两种


DEBUG 2016-08-29 20:08:09,499 org.mybatis.spring.SqlSessionUtils: Creating a new SqlSession
DEBUG 2016-08-29 20:08:09,499 org.mybatis.spring.SqlSessionUtils: SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@253d9f73] was not registered for synchronization because synchronization is not active
DEBUG 2016-08-29 20:08:09,499 org.apache.ibatis.cache.decorators.LoggingCache: Cache Hit Ratio [com.we.dao.PersonDao]: 0.75
DEBUG 2016-08-29 20:08:09,499 org.mybatis.spring.SqlSessionUtils: Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@253d9f73]





2
DEBUG 2016-08-29 20:05:25,212 org.mybatis.spring.SqlSessionUtils: Creating a new SqlSession
DEBUG 2016-08-29 20:05:25,212 org.mybatis.spring.SqlSessionUtils: SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1941a8ff] was not registered for synchronization because synchronization is not active
DEBUG 2016-08-29 20:05:25,212 org.springframework.jdbc.datasource.DataSourceUtils: Fetching JDBC Connection from DataSource
DEBUG 2016-08-29 20:05:25,212 org.mybatis.spring.transaction.SpringManagedTransaction: JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@2e1ef60] will not be managed by Spring
DEBUG 2016-08-29 20:05:25,212 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from person WHERE id=? 
DEBUG 2016-08-29 20:05:25,212 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 1(Integer)
DEBUG 2016-08-29 20:05:25,228 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 1
DEBUG 2016-08-29 20:05:25,228 org.mybatis.spring.SqlSessionUtils: Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1941a8ff]
DEBUG 2016-08-29 20:05:25,228 org.springframework.jdbc.datasource.DataSourceUtils: Returning JDBC Connection to DataSource
3






四 配置Ehcache:加入jar包


net.sf.ehcache
ehcache-core
2.6.11


org.mybatis
mybatis-ehcache
1.0.0

然后把上面的cacha换成下面两个的任意一个。可以看一下两个类的实现就可以发现,LoggingEhcache是对EhcacheCache的包装。(LoggingEhcache的构造方法)
     
      



五:配置redis缓存  

MyBatis配置redis需要实现org.apache.ibatis.cache.Cache接口,然后把四中的类改为自己写的类就行了。例子待续。




注意:在cache标签中还有好几个属性需要挖掘。比如说eviction是配置缓存策略。还有


你可能感兴趣的:(mybatis)