SqlSessionFactory 的openSession方法
来源:互联网 发布:opengl linux 下载 编辑:程序博客网 时间:2024/06/10 01:00
public SqlSessionopenSession() { returnopenSessionFromDataSource(configuration.getDefaultExecutorType(),null, false); } 我们可以看到实际创建SqlSession的地方是openSessionFromDataSource,如下:[java] view plain copyprivate SqlSessionopenSessionFromDataSource(ExecutorType execType, TransactionIsolationLevellevel, boolean autoCommit) { Connectionconnection = null; try { finalEnvironment environment = configuration.getEnvironment(); final DataSourcedataSource = getDataSourceFromEnvironment(environment); TransactionFactory transactionFactory =getTransactionFactoryFromEnvironment(environment); connection = dataSource.getConnection(); if (level != null) { connection.setTransactionIsolation(level.getLevel()); } connection = wrapConnection(connection); Transaction tx = transactionFactory.newTransaction(connection,autoCommit); Executorexecutor = configuration.newExecutor(tx, execType); returnnewDefaultSqlSession(configuration, executor, autoCommit); } catch (Exceptione) { closeConnection(connection); throwExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
可以看出,创建sqlsession经过了以下几个主要步骤:
1) 从配置中获取Environment;
2) 从Environment中取得DataSource;
3) 从Environment中取得TransactionFactory;
4) 从DataSource里获取数据库连接对象Connection;
5) 在取得的数据库连接上创建事务对象Transaction;
6) 创建Executor对象(该对象非常重要,事实上sqlsession的所有操作都是通过它完成的);
7) 创建sqlsession对象。
Executor的创建
Executor与Sqlsession的关系就像市长与书记,Sqlsession只是个门面,真正干事的是Executor,Sqlsession对数据库的操作都是通过Executor来完成的。与Sqlsession一样,Executor也是动态创建的:
public ExecutornewExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType :executorType; executorType = executorType == null ?ExecutorType.SIMPLE : executorType; Executor executor; if(ExecutorType.BATCH == executorType) { executor = new BatchExecutor(this,transaction); } elseif(ExecutorType.REUSE == executorType) { executor = new ReuseExecutor(this,transaction); } else { executor = newSimpleExecutor(this, transaction); } if (cacheEnabled) { executor = new CachingExecutor(executor); } executor =(Executor) interceptorChain.pluginAll(executor); return executor; }
可以看出,如果不开启cache的话,创建的Executor只是3中基础类型之一,BatchExecutor专门用于执行批量sql操作,ReuseExecutor会重用statement执行sql操作,SimpleExecutor只是简单执行sql没有什么特别的。开启cache的话(默认是开启的并且没有任何理由去关闭它),就会创建CachingExecutor,它以前面创建的Executor作为唯一参数。CachingExecutor在查询数据库前先查找缓存,若没找到的话调用delegate(就是构造时传入的Executor对象)从数据库查询,并将查询结果存入缓存中。
Executor对象是可以被插件拦截的,如果定义了针对Executor类型的插件,最终生成的Executor对象是被各个插件插入后的代理对象
Mapper
Mybatis官方手册建议通过mapper对象访问mybatis,因为使用mapper看起来更优雅,就像下面这样:
session = sqlSessionFactory.openSession(); UserDao userDao= session.getMapper(UserDao.class); UserDto user =new UserDto(); user.setUsername("iMbatis"); user.setPassword("iMbatis"); userDao.insertUser(user);
看起来没什么特别的,和其他代理类的创建一样,我们重点关注一下MapperProxy的invoke方法
MapperProxy的invoke
我们知道对被代理对象的方法的访问都会落实到代理者的invoke上来,MapperProxy的invoke如下:
public Objectinvoke(Object proxy, Method method, Object[] args) throws Throwable{ if (method.getDeclaringClass()== Object.class) { return method.invoke(this, args); } finalClass<?> declaringInterface = findDeclaringInterface(proxy, method); finalMapperMethod mapperMethod = newMapperMethod(declaringInterface, method, sqlSession); final Objectresult = mapperMethod.execute(args); if (result ==null && method.getReturnType().isPrimitive()&& !method.getReturnType().equals(Void.TYPE)) { thrownewBindingException("Mapper method '" + method.getName() + "'(" + method.getDeclaringClass() + ") attempted toreturn null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; } 可以看到invoke把执行权转交给了MapperMethod,我们来看看MapperMethod里又是怎么运作的:[java] view plain copy public Objectexecute(Object[] args) { Objectresult = null; if(SqlCommandType.INSERT == type) { Objectparam = getParam(args); result= sqlSession.insert(commandName, param); } elseif(SqlCommandType.UPDATE == type) { Object param = getParam(args); result= sqlSession.update(commandName, param); } elseif(SqlCommandType.DELETE == type) { Objectparam = getParam(args); result= sqlSession.delete(commandName, param); } elseif(SqlCommandType.SELECT == type) { if (returnsVoid &&resultHandlerIndex != null) { executeWithResultHandler(args); } elseif (returnsList) { result = executeForList(args); } elseif (returnsMap) { result = executeForMap(args); } else { Object param = getParam(args); result = sqlSession.selectOne(commandName, param); } } else { thrownewBindingException("Unknown execution method for: " + commandName); } return result; }
可以看到,MapperMethod就像是一个分发者,他根据参数和返回值类型选择不同的sqlsession方法来执行。这样mapper对象与sqlsession就真正的关联起来了
- SqlSessionFactory 的openSession方法
- openSession()和getCurrentSession()两个方法的区别
- 封装SqlSessionFactory调用方法
- session的openSession()方法与getCurrentSession()方法的区别
- hibernate中openSession()方法和getCurrentSession()方法的区别
- mybatis的sqlsessionFactory
- Hibernate SessionFactory中openSession和getCurrentSession方法的区别
- Hibernate SessionFactory中openSession和getCurrentSession方法的区别
- Hibernate 中的 openSession和getCurrentSession 方法的区别
- MyBatis核心SqlSessionFactory的创建
- MyBatis核心SqlSessionFactory的创建
- MyBatis核心SqlSessionFactory的创建
- spring配置mybatis的sqlsessionfactory
- openSession
- mybatis中获取SqlSessionFactory的几种方法及其相关使用
- hibernate获取session的两种方式分别是openSession() 方法和getCurrentSession() 方法。
- getCurrentSession 与 openSession() 的区别 getCurrentSession 与 openSession() 的区别
- 对于Hibernate的openSession方法为什么不是线程安全的源码理解
- 创建一个项目
- 异步采数据 asynchapp程序
- OpenMP并行程序设计——for循环并行化详解
- 为什么公司网页无法加载,游戏无法正常运行,点这里!
- 解决VC++编译程序出现中文乱码的问题
- SqlSessionFactory 的openSession方法
- ajax请求过程
- eval调研
- AS开发中出现Error(三)——Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cru
- Android 6.0 运行时权限处理终结全网请求权限开源库出现的各种坑包括认为是google的bug
- 计算机图形学(四)几何变换_5_三维空间的几何变换_1_三维平移
- 精通正则表达式一:元字符
- Android CMake 使用Android Native library
- 欢迎使用CSDN-markdown编辑器