mybaties使用过程及原理

mybaties使用过程及原理mybaties 使用过程及原理 1 加载 xml 配置 读取 bean 文件 dataSource 和 mapper 文件的位置 并返回 factory 对象 SqlSessionFa newSqlSessio build newFileInput conf configeratio xml xml 如下 xml

 
   
   
    
    
     
    
    
     
      
      
      
      
       
       
       
       
      
     
    
    
     
    
   

biuld()方法如下:

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { inputStream.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } } 
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); } private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { final Environment environment = configuration.getEnvironment(); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); final Executor executor = configuration.newExecutor(tx, execType); return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { closeTransaction(tx); // may have fetched a connection so lets call close() throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } 
@SuppressWarnings("unchecked") public 
  
    T getMapper(Class 
   
     type, SqlSession sqlSession) { final MapperProxyFactory 
    
      mapperProxyFactory = (MapperProxyFactory 
     
       ) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } } public T newInstance(SqlSession sqlSession) { final MapperProxy 
      
        mapperProxy = new MapperProxy 
       
         (sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } 
        
       
      
     
    
  

这里返回了代理对象:

 @SuppressWarnings("unchecked") protected T newInstance(MapperProxy 
  
    mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); } 
  

下面是handler里的invoke方法,所以当你调用dao.selectAll()方法时会走到invoke方法,而在invoke方法里又调用了sqlsession的selectList()方法:

@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (Object.class.equals(method.getDeclaringClass())) { try { return method.invoke(this, args); } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } } final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); } 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; } else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } 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; } 
 
   
    
    
    
    
   

2创建sqlsessionFactory,把datasource传入

 
   
    
    
    
    
    
    
     
     
       classpath:com/bdqn/dao//*.xml 
      
     
    
   

3创建sqlsessiontemplete

 
   
   
    
   

4sqlsessionTemplete可以通过getMapper()获取到代理对象。

5在sping.xml同样可以配置MapperScannerConfiger,就可以自动扫码@Mapeper注解

 
   
   
   
    
    
    
    
    
   
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/220334.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午8:44
下一篇 2026年3月17日 下午8:45


相关推荐

  • 【git系列】切换分支相关命令

    【git系列】切换分支相关命令背景为什么小编突然整理出这样一份命令呢?起因还是目前的工作项目的微服务太多,使用idea切换分支时,很容易点错或者合并错分支代码,于是小编下定决心,放弃使用工具切换分支,使用命令操作,使用之后发现爽的一批,操作起来666的,同时也希望帮助小伙伴们快速入门Git操作分支;命令命令的含义和介绍这些八股文,小编不再累赘,直接上命令创建并切换到本地分支gitcheckout-b分支名切换分支gitcheckout分支名两者的区别是否带-b提交分支到远程仓库(本地分支与

    2022年6月20日
    37
  • Android开发必备工具

    Android开发必备工具工欲善其事,必先利其器,在Android项目的开发中,借助工具能使开发效率大幅提升,下面分享我经常使用的工具,欢迎各位同学补充。1.AndroidStudioAndroid程序员的吃饭工具,可以说现在绝大部分的安卓项目都是跑在AndroidStudio上面的。AndroidStudio是基于IntelliJIDEA且适用于开发Android应用的官方集成开发环境(IDE…

    2022年6月7日
    39
  • 妙计想了一千五,明朝依旧卖豆腐[通俗易懂]

    妙计想了一千五,明朝依旧卖豆腐

    2022年3月6日
    62
  • Python urllib库

    Python urllib库转自 https blog csdn net bo mask article details 使用 urllib 在 Python2 版本中 有 urllib 和 urlib2 两个库可以用来实现 request 的发送 在 Python3 中 已经不存在 urllib2 这个库了 统一为 urllib Python3urlli 库官方链接 nbsp Python3urlli 官方链接 urllib 中包括了四个模块

    2026年3月19日
    3
  • Spring Boot面试题(2020最新版)

    Spring Boot面试题(2020最新版)文章目录概述什么是SpringBoot?SpringBoot有哪些优点?SpringBoot的核心注解是哪个?它主要由哪几个注解组成的?配置什么是JavaConfig?SpringBoot自动配置原理是什么?你如何理解SpringBoot配置加载顺序?什么是YAML?YAML配置的优势在哪里?SpringBoot是否可以使用XML配置?springboot…

    2022年5月2日
    54
  • Kafka 集群 Golang 应用实例

    Kafka 集群 Golang 应用实例

    2021年6月30日
    100

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号