电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

瀏覽:6日期:2023-07-16 14:24:24

1.在下面的案例中,執行兩次查詢控制臺只會輸出一次 SQL 查詢:

mybatis-config.xml<?xml version='1.0' encoding='UTF-8' ?><!DOCTYPE configurationPUBLIC '-//mybatis.org//DTD Config 3.0//EN''http://mybatis.org/dtd/mybatis-3-config.dtd'><configuration> <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/xxx?useUnicode=true&characterEncoding=utf-8&autoReconnect=true'/><property name='username' value='xxx'/><property name='password' value='xxx'/> </dataSource></environment> </environments> <mappers><mapper resource='com/hrh/mapper/PersonMapper.xml'/> </mappers></configuration>

PersonMapper.xml<?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='com.hrh.mapper.PersonMapper'> <resultMap type='com.hrh.bean.Person'><id column='id' property='id' jdbcType='BIGINT'/><result column='name' property='name' jdbcType='VARCHAR'/><result column='age' property='age' jdbcType='BIGINT'/> </resultMap> <sql id='Base_Column_List'> id, name, age </sql> <select resultType='com.hrh.bean.Person'>select<include refid='Base_Column_List'/>from tab_person </select></mapper>

public interface PersonMapper { List<Person> list();}

String resource = 'mybatis-config2.xml';InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//開啟會話PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);mapper.list();mapper.list();

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

之所以會出現這種情況,是因為 Mybatis 存在一級緩存導致的,下面 debug 探究下內部流程:

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

(1)mapper.list() 會進入 MapperProxy#invoke():參數proxy是一個代理對象(每個 Mapper 接口都會被轉換成一個代理對象),里面包含會話 sqlSession、接口信息、方法信息;method是目標方法(當前執行的方法),它里面包含了所屬的哪個類(接口)、方法名、返回類型(List、Map、void 或其他)、參數類型等;args是參數;

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) {return method.invoke(this, args); } else if (isDefaultMethod(method)) {return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //從方法緩存methodCache中獲取到方法的信息:比如方法名、類型(select、update等)、返回類型 //如果獲取中沒有MapperMethod,則創建一個并放入methodCache中 final MapperMethod mapperMethod = cachedMapperMethod(method); //執行查詢SQL并返回結果 return mapperMethod.execute(sqlSession, args); }

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

cacheMapperMethod:MapperMethod 包含方法名、類型(select、update等)、返回類型等信息

private MapperMethod cachedMapperMethod(Method method) { //緩存中獲取 MapperMethod mapperMethod = methodCache.get(method); //沒有則創建一個對象并放入緩存中供下次方便取用 if (mapperMethod == null) { mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); methodCache.put(method, mapperMethod); } return mapperMethod; }

(2)MapperMethod#execute()根據 SQL 類型進入不同的查詢方法

public Object execute(SqlSession sqlSession, Object[] args) { //返回結果 Object result; //判斷語句類型 switch (command.getType()) { case INSERT: {//插入語句 Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.insert(command.getName(), param));break; } case UPDATE: {//更新語句Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.update(command.getName(), param));break; } case DELETE: {//刪除語句Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.delete(command.getName(), param));break; } case SELECT://查詢語句//返回空的查詢if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; //返回List的查詢} else if (method.returnsMany()) { result = executeForMany(sqlSession, args); //返回Map的查詢} else if (method.returnsMap()) { result = executeForMap(sqlSession, args); //返回游標的查詢} else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args);} else { Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param);}break; case FLUSH:result = sqlSession.flushStatements();break; default:throw new BindingException('Unknown execution method for: ' + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException('Mapper method ’' + command.getName() + ' attempted to return null from a method with a primitive return type (' + method.getReturnType() + ').'); } return result; }

(3)上面的案例是 select 語句,返回結果是List集合,所以進入 MapperMethod#executeForMany():

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { List<E> result; //獲取參數 Object param = method.convertArgsToSqlCommandParam(args); //是否有分頁查詢 if (method.hasRowBounds()) { RowBounds rowBounds = method.extractRowBounds(args); result = sqlSession.<E>selectList(command.getName(), param, rowBounds); } else { result = sqlSession.<E>selectList(command.getName(), param); } // issue #510 Collections & arrays support //如果list中的泛型跟結果類型不一致,進行轉換 if (!method.getReturnType().isAssignableFrom(result.getClass())) { if (method.getReturnType().isArray()) {return convertToArray(result); } else {return convertToDeclaredCollection(sqlSession.getConfiguration(), result); } } return result; }

(4)selectList執行了DefaultSqlSession#selectList():

public <E> List<E> selectList(String statement, Object parameter) { return this.selectList(statement, parameter, RowBounds.DEFAULT); }

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { try { //SQL執行的信息:resource(xxMapper.xml)、id、sql、返回類型等 MappedStatement ms = configuration.getMappedStatement(statement); //執行查詢 return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException('Error querying database. Cause: ' + e, e); } finally { ErrorContext.instance().reset(); } }

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

(5)接下來調用緩存執行器的方法:CachingExecutor#query()

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { //獲取到執行SQL BoundSql boundSql = ms.getBoundSql(parameterObject); //將SQL包裝成一個緩存對對象,該對象和結果集組成鍵值對存儲到緩存中,方便下次直接從緩存中拿而不需要再次查詢 //createCacheKey:調用BaseExecutor#createCacheKey CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql); return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { //獲取緩存 Cache cache = ms.getCache(); if (cache != null) { flushCacheIfRequired(ms); if (ms.isUseCache() && resultHandler == null) {ensureNoOutParams(ms, boundSql);@SuppressWarnings('unchecked')List<E> list = (List<E>) tcm.getObject(cache, key);if (list == null) { list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); // issue #578 and #116}return list; } } //沒有緩存連接查詢 return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }

(6)接下來執行 BaseExecutor#query():從下面可以看到將結果緩存到localCache 中了

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { ErrorContext.instance().resource(ms.getResource()).activity('executing a query').object(ms.getId()); if (closed) { throw new ExecutorException('Executor was closed.'); } //如果不是嵌套查詢(默認為0),且 <select> 的 flushCache=true 時清空緩存 if (queryStack == 0 && ms.isFlushCacheRequired()) { clearLocalCache(); } List<E> list; try { //嵌套查詢層數+1 queryStack++; //從localCache緩存中獲取 list = resultHandler == null ? (List<E>) localCache.getObject(key) : null; if (list != null) {handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); } else {//連接查詢list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); } } finally { queryStack--; } //下面是延遲加載邏輯 if (queryStack == 0) { for (DeferredLoad deferredLoad : deferredLoads) {deferredLoad.load(); } // issue #601 deferredLoads.clear(); if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {// issue #482clearLocalCache(); } } return list; }

private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { List<E> list; //緩存中添加占位符 localCache.putObject(key, EXECUTION_PLACEHOLDER); try { //連接查詢獲取到數據結果 list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); } finally { //刪除占位符 localCache.removeObject(key); } //將結果緩存起來 localCache.putObject(key, list); //處理存儲過程 if (ms.getStatementType() == StatementType.CALLABLE) { localOutputParameterCache.putObject(key, parameter); } return list; }

2.但當 Spring Framework + Mybatis 時,情況就不一樣了,每次查詢都會連接數據庫查詢,控制臺都會打印 SQL 出來,如下案例:

@Servicepublic class PersonService { @Autowired PersonMapper personMapper; public List<Person> getList() {personMapper.list();personMapper.list();return personMapper.list(); }}

@Configuration@ComponentScan('com.hrh')@MapperScan('com.hrh.mapper')public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactory() throws Exception {SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource());factoryBean.setMapperLocations(resolveMapperLocations());return factoryBean; } public Resource[] resolveMapperLocations() {ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();List<String> mapperLocations = new ArrayList<>();mapperLocations.add('classpath*:com/hrh/mapper/*Mapper*.xml');List<Resource> resources = new ArrayList();if (mapperLocations != null) { for (String mapperLocation : mapperLocations) {try { Resource[] mappers = resourceResolver.getResources(mapperLocation); resources.addAll(Arrays.asList(mappers));} catch (IOException e) { // ignore} }}return resources.toArray(new Resource[resources.size()]); } @Bean public DataSource dataSource() {DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setDriverClassName('com.mysql.jdbc.Driver');driverManagerDataSource.setUsername('xxx');driverManagerDataSource.setPassword('xxx');driverManagerDataSource.setUrl('jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&autoReconnect=true');return driverManagerDataSource; }}

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBatisConfig.class);PersonService bean = context.getBean(PersonService.class);bean.getList();

Mybatis一級緩存和結合Spring Framework后失效的源碼探究

下面debug進入的步驟跟上面的(1)、(2)、(3)是一致的,但第四步卻是進入SqlSessionTemplate#selectList()中【SqlSessionTemplate是mybatis-spring-xx.jar的,上文的DefaultSqlSession是屬于mybatis-xx.jar的】:

public <E> List<E> selectList(String statement, Object parameter) { return this.selectList(statement, parameter, RowBounds.DEFAULT); }

接下來的selectList() 會被方法攔截:method.invoke() 會執行到 DefaultSqlSession#selectList(),重新回到上文的第四步并且繼續下去,也就是在上文的(1)~(6)中插入了前后文,在其中做了關閉會話的操作;

private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //得到會話 SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try {//執行方法查詢Object result = method.invoke(sqlSession, args);if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true);//在關閉會話前提交和回滾}return result; } catch (Throwable t) {//有異常拋出異常并結束會話Throwable unwrapped = unwrapThrowable(t);if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; }}throw unwrapped; } finally {//關閉會話if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);} } } }總結:

Mybatis 的一級緩存是會話級別的緩存(單線程的,特別雞肋),Mybatis 每創建一個 SqlSession 會話對象,就表示打開一次數據庫會話,在一次會話中,應用程序很可能在短時間內反復執行相同的查詢語句,如果不對數據進行緩存,則每查詢一次就要執行一次數據庫查詢,這就造成數據庫資源的浪費。又因為通過 SqlSession 執行的操作,實際上由 Executor 來完成數據庫操作的,所以在 Executor 中會建立一個簡單的緩存,即一級緩存;將每次的查詢結果緩存起來,再次執行查詢的時候,會先查詢一級緩存(默認開啟的),如果命中,則直接返回,否則再去查詢數據庫并放入緩存中。

一級緩存的生命周期與 SqlSession 的生命周期相同,因此當 Mybatis 和Spring Framework 的集成包中擴展了一個 SqlSessionTemplate 類(它是一個代理類,增強了查詢方法),所有的查詢經過 SqlSessionTemplate 代理攔截后再進入到 DefaultSqlSession#selectList() 中,結束查詢后把會話SqlSession 關了,所以導致了緩存失效。

那為什么要這么操作呢?

原始的 Mybatis 有暴露 SqlSession 接口,因此有 close 方法暴露出來供你選擇使用,你可以選擇關與不關,但在Mybatis 和Spring Framework 的集成包中,SqlSession 是交給了Spring Framework 管理的,沒有暴露出來,為了穩妥決定,直接給你關了。

到此這篇關于Mybatis一級緩存和結合Spring Framework后失效的源碼探究的文章就介紹到這了,更多相關Mybatis一級緩存Spring Framework失效內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: led冷热冲击试验箱_LED高低温冲击试验箱_老化试验箱-爱佩百科 | 东亚液氮罐-液氮生物容器-乐山市东亚机电工贸有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 至顶网| 流变仪-热分析联用仪-热膨胀仪厂家-耐驰科学仪器商贸 | 淬火设备-钎焊机-熔炼炉-中频炉-锻造炉-感应加热电源-退火机-热处理设备-优造节能 | 【中联邦】增稠剂_增稠粉_水性增稠剂_涂料增稠剂_工业增稠剂生产厂家 | 美侍宠物-专注宠物狗及宠物猫训练|喂养|医疗|繁育|品种|价格 | BESWICK球阀,BESWICK接头,BURKERT膜片阀,美国SEL继电器-东莞市广联自动化科技有限公司 | 多功能三相相位伏安表-变压器短路阻抗测试仪-上海妙定电气 | 自恢复保险丝_贴片保险丝_力特保险丝_Littelfuse_可恢复保险丝供应商-秦晋电子 | 不锈钢反应釜,不锈钢反应釜厂家-价格-威海鑫泰化工机械有限公司 不干胶标签-不干胶贴纸-不干胶标签定制-不干胶标签印刷厂-弗雷曼纸业(苏州)有限公司 | 光环国际-新三板公司_股票代码:838504 | 污水处理设备维修_污水处理工程改造_机械格栅_过滤设备_气浮设备_刮吸泥机_污泥浓缩罐_污水处理设备_污水处理工程-北京龙泉新禹科技有限公司 | 钢衬玻璃厂家,钢衬玻璃管道 -山东东兴扬防腐设备有限公司 | 北京网络营销推广_百度SEO搜索引擎优化公司_网站排名优化_谷歌SEO - 北京卓立海创信息技术有限公司 | 机构创新组合设计实验台_液压实验台_气动实训台-戴育教仪厂 | 电动葫芦|环链电动葫芦-北京凌鹰名优起重葫芦 | 百度关键词优化_网站优化_SEO价格 - 云无限好排名 | 真空包装机-诸城市坤泰食品机械有限公司| 短信通106短信接口验证码接口群发平台_国际短信接口验证码接口群发平台-速度网络有限公司 | 震动筛选机|震动分筛机|筛粉机|振筛机|振荡筛-振动筛分设备专业生产厂家高服机械 | 高通量组织研磨仪-多样品组织研磨仪-全自动组织研磨仪-研磨者科技(广州)有限公司 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | 电镀标牌_电铸标牌_金属标贴_不锈钢标牌厂家_深圳市宝利丰精密科技有限公司 | 贴片电容代理-三星电容-村田电容-风华电容-国巨电容-深圳市昂洋科技有限公司 | 干培两用箱-细菌恒温培养箱-菲斯福仪器| 附着力促进剂-尼龙处理剂-PP处理剂-金属附着力处理剂-东莞市炅盛塑胶科技有限公司 | 西安中国国际旅行社(西安国旅) | 防勒索软件_数据防泄密_Trellix(原McAfee)核心代理商_Trellix(原Fireeye)售后-广州文智信息科技有限公司 | 汽车水泵_汽车水泵厂家-瑞安市骏迪汽车配件有限公司 | 三氯异氰尿酸-二氯-三氯-二氯异氰尿酸钠-优氯净-强氯精-消毒片-济南中北_优氯净厂家 | 广东风淋室_广东风淋室厂家_广东风淋室价格_广州开源_传递窗_FFU-广州开源净化科技有限公司 | 自动钻孔机-全自动数控钻孔机生产厂家-多米(广东)智能装备有限公司 | 金联宇电缆总代理-金联宇集团-广东金联宇电缆实业有限公司 | 热缩管切管机-超声波切带机-织带切带机-无纺布切布机-深圳市宸兴业科技有限公司 | 西点培训学校_法式西点培训班_西点师培训_西点蛋糕培训-广州烘趣西点烘焙培训学院 | 网络推广公司_网络营销方案策划_企业网络推广外包平台-上海澜推网络 | 砍排机-锯骨机-冻肉切丁机-熟肉切片机-预制菜生产线一站式服务厂商 - 广州市祥九瑞盈机械设备有限公司 | 耐酸碱泵-自吸耐酸碱泵型号「品牌厂家」立式耐酸碱泵价格-昆山国宝过滤机有限公司首页 | 优秀的临床医学知识库,临床知识库,医疗知识库,满足电子病历四级要求,免费试用 |