Mybatis工作机制源码分析—SqlSessionUtils.getSqlSession工作机制
来源:互联网 发布:鹿晗同性倾向 知乎 编辑:程序博客网 时间:2024/05/17 10:40
在调用SqlSessionTemplate进行dao层操作时,其会将工作委托给sqlSessionProxy属性进行,而sqlSessionProxy在进行相关method调用时,用到了JDK动态代理机制,首先SqlSessionUtils.getSqlSession获取sqlSession,本文主要以源码的形式阐述其工作机制。
SqlSessionTemplate.SqlSessionInterceptor源码
private class SqlSessionInterceptor implements InvocationHandler {public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 首先获取sqlSessionfinal SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory,SqlSessionTemplate.this.executorType,SqlSessionTemplate.this.exceptionTranslator);try {// JDK动态代理反射机制Object result = method.invoke(sqlSession, args);if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {sqlSession.commit();}return result;} catch (Throwable t) {Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {unwrapped = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);}throw unwrapped;} finally {SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);}}}
SqlSessionUtils.getSqlSession源码
dataSource不为TransactionAwareDataSourceProxy时,采用DataSourceUtils.getConnection(dataSource)获取实际的Connection:
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {Assert.notNull(sessionFactory, "No SqlSessionFactory specified");Assert.notNull(executorType, "No ExecutorType specified");// 事务同步资源管理SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);if (holder != null && holder.isSynchronizedWithTransaction()) {if (holder.getExecutorType() != executorType) {throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");}holder.requested();if (logger.isDebugEnabled()) {logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");}return holder.getSqlSession();}// 获取dataSourceDataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource();// SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but // we keep this check for the case that SqlSessionUtils is called from custom codeboolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);Connection conn;try {// 实际Connection的获取conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource);} catch (SQLException e) {throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e);}if (logger.isDebugEnabled()) {logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]");}// Assume either DataSourceTransactionManager or the underlying// connection pool already dealt with enabling auto commit.// This may not be a good assumption, but the overhead of checking// connection.getAutoCommit() again may be expensive (?) in some drivers// (see DataSourceTransactionManager.doBegin()). One option would be to// only check for auto commit if this function is being called outside// of DSTxMgr, but to do that we would need to be able to call// ConnectionHolder.isTransactionActive(), which is protected and not// visible to this class.// 基于Connection,创建SqlSessionSqlSession session = sessionFactory.openSession(executorType, conn);// Register session holder and bind it to enable synchronization.//// Note: The DataSource should be synchronized with the transaction// either through DataSourceTxMgr or another tx synchronization.// Further assume that if an exception is thrown, whatever started the transaction will// handle closing / rolling back the Connection associated with the SqlSession.if (TransactionSynchronizationManager.isSynchronizationActive()) {// 事务同步下的对资源相关操作if (!(sessionFactory.getConfiguration().getEnvironment().getTransactionFactory() instanceof SpringManagedTransactionFactory)&& DataSourceUtils.isConnectionTransactional(conn, dataSource)) {throw new TransientDataAccessResourceException("SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");}if (logger.isDebugEnabled()) {logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");}holder = new SqlSessionHolder(session, executorType, exceptionTranslator);TransactionSynchronizationManager.bindResource(sessionFactory, holder);TransactionSynchronizationManager.registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));holder.setSynchronizedWithTransaction(true);holder.requested();} else {if (logger.isDebugEnabled()) {logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active");} }return session;}
DataSourceUtils.getConnection源码
DataSourceUtils.java// 获取Connectionpublic static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {try {return doGetConnection(dataSource);}catch (SQLException ex) {throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);}}public static Connection doGetConnection(DataSource dataSource) throws SQLException {Assert.notNull(dataSource, "No DataSource specified");// 事务同步管理下的对应ConnectionHolder资源获取ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {conHolder.requested();if (!conHolder.hasConnection()) {logger.debug("Fetching resumed JDBC Connection from DataSource");conHolder.setConnection(dataSource.getConnection());}return conHolder.getConnection();}// Else we either got no holder or an empty thread-bound holder here.logger.debug("Fetching JDBC Connection from DataSource");// 直接从dataSource中获取JDBC连接Connection con = dataSource.getConnection();if (TransactionSynchronizationManager.isSynchronizationActive()) {// 事务同步管理下,对ConnectionHolder资源的操作logger.debug("Registering transaction synchronization for JDBC Connection");// Use same Connection for further JDBC actions within the transaction.// Thread-bound object will get removed by synchronization at transaction completion.ConnectionHolder holderToUse = conHolder;if (holderToUse == null) {holderToUse = new ConnectionHolder(con);}else {holderToUse.setConnection(con);}holderToUse.requested();TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource));holderToUse.setSynchronizedWithTransaction(true);if (holderToUse != conHolder) {TransactionSynchronizationManager.bindResource(dataSource, holderToUse);}}return con;}
采用源码的形式了解Mybatis如何基于Spring获取Connection。
阅读全文
2 0
- Mybatis工作机制源码分析—SqlSessionUtils.getSqlSession工作机制
- Mybatis工作机制源码分析—初始化
- Mybatis工作机制源码分析—初始化—sax解析
- Mybatis工作机制源码分析—缓存机制及事务机制
- Springmvc 工作机制源码分析
- Struts2工作机制源码分析
- Mybatis工作机制源码分析—初始化—config配置文件解析
- Mybatis工作机制源码分析—初始化—mapper配置文件解析
- Mybatis工作机制源码分析—一次insert请求处理流程
- Mybatis工作机制源码分析—一次select请求处理流程
- kubeadm工作机制分析
- kubeadm工作机制分析
- 分析ClassLoader工作机制
- Vold工作机制分析
- Android源码分析--Handler机制的实现与工作原理
- Linux操作系统工作机制分析
- Java IO工作机制分析
- 深入分析ClassLoader工作机制
- 在linux中用C语言实现ping命令
- phonewindow视图结构
- jquery基本选择器
- 分享-struts2的AJAX怎么实现
- C/C++——为什么类的静态成员函数在定义的时候不写static?
- Mybatis工作机制源码分析—SqlSessionUtils.getSqlSession工作机制
- MySQL优化原理
- AJAX学习笔记
- 1.storm问题总结 Could not find leader nimbus from seed hosts [localhost] Did you specify a valid list of
- 最小割——BZOJ1412/Luogu2598 [ZJOI2009]狼和羊的故事
- 图像轮廓生成Freeman码
- MySql高级知识的一些总结
- idea快捷键
- 微服务框架下的思维变化-OSS.Core基础思路