标签:apache jdbc 安全 code 过程 ace dynamic ret 注意
二级缓存(全局缓存):基于namespace级别的缓存,一个namespace对应一个二级缓存。
工作机制:
使用过程:
<setting name="lazyLoadingEnabled" value="true"/>
<mapper namespace="com.gong.mybatis.dao.EmployeeMapper"> <cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"> <!-- eviction:缓存的回收策略,默认LRU flushInterval:缓存刷新间隔,默认不清空,可以设置一个毫秒值 readOnly:只读为true,所有从缓存中获取操作都是只读操作,不会修改数据,直接将数据在缓存中的引用交给用户; 非只读,获取的数据可能会被修改,会利用序列化&反序列化的技术克隆一份新的数据,安全,但速度慢。 size:缓存存放多少元素 type:指定自定义缓存的全类名,实现Cache接口即可 --> </cache> ...... </mapper>
public class Employee implements Serializable
测试:
package com.gong.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.gong.mybatis.bean.Department; import com.gong.mybatis.bean.Employee; import com.gong.mybatis.dao.EmployeeMapper; import com.gong.mybatis.mapper.EmployeeMapperDynamicSql; public class TestMybatis4 { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(is); } @Test public void test() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); SqlSession openSession2 = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class); Employee em = mapper.getEmpById(1); System.out.println(em); openSession.close(); Employee em2 = mapper2.getEmpById(1); System.out.println(em2); openSession.close(); } finally { // TODO: handle finally clause } } }
输出:
DEBUG 01-22 10:59:28,726 Cache Hit Ratio [com.gong.mybatis.dao.EmployeeMapper]: 0.0 (LoggingCache.java:62) DEBUG 01-22 10:59:29,055 ==> Preparing: select id,last_name lastName,email,gender from tbl_employee where id = ? (BaseJdbcLogger.java:145) DEBUG 01-22 10:59:29,102 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145) DEBUG 01-22 10:59:29,148 <== Total: 1 (BaseJdbcLogger.java:145) Employee [id=1, lastName=dema, gender=1, email=dema@qq.com, dept=null] DEBUG 01-22 10:59:29,242 Cache Hit Ratio [com.gong.mybatis.dao.EmployeeMapper]: 0.5 (LoggingCache.java:62) Employee [id=1, lastName=dema, gender=1, email=dema@qq.com, dept=null]
需要注意是要在第一个会话结束之后要先关闭,否则如果在最后一起关闭,就变成一级缓存的情况了。
和缓存相关的设置:
标签:apache jdbc 安全 code 过程 ace dynamic ret 注意
原文地址:https://www.cnblogs.com/xiximayou/p/12228177.html