深入浅出MyBatis-Sqlsession

来源:互联网 发布:体检数据服务 编辑:程序博客网 时间:2024/04/28 10:25

转自:http://blog.csdn.net/hupanfeng/article/details/9238127

创建

正如其名,Sqlsession对应着一次数据库会话。由于数据库回话不是永久的,因此Sqlsession的生命周期也不应该是永久的,相反,在你每次访问数据库时都需要创建它(当然并不是说在Sqlsession里只能执行一次sql,你可以执行多次,当一旦关闭了Sqlsession就需要重新创建它)。创建Sqlsession的地方只有一个,那就是SqlsessionFactory的openSession方法:

[java] view plain copy
  1. public SqlSessionopenSession() {  
  2.     returnopenSessionFromDataSource(configuration.getDefaultExecutorType(),nullfalse);  
  3. }  

我们可以看到实际创建SqlSession的地方是openSessionFromDataSource,如下:

[java] view plain copy
  1. private SqlSessionopenSessionFromDataSource(ExecutorType execType, TransactionIsolationLevellevel, boolean autoCommit) {  
  2.   
  3.     Connectionconnection = null;  
  4.   
  5.     try {  
  6.   
  7.         finalEnvironment environment = configuration.getEnvironment();  
  8.   
  9.         final DataSourcedataSource = getDataSourceFromEnvironment(environment);  
  10.   
  11.        TransactionFactory transactionFactory =getTransactionFactoryFromEnvironment(environment);  
  12.   
  13.        connection = dataSource.getConnection();  
  14.   
  15.         if (level != null) {  
  16.   
  17.            connection.setTransactionIsolation(level.getLevel());  
  18.   
  19.         }  
  20.   
  21.        connection = wrapConnection(connection);  
  22.   
  23.        Transaction tx = transactionFactory.newTransaction(connection,autoCommit);  
  24.   
  25.         Executorexecutor = configuration.newExecutor(tx, execType);  
  26.   
  27.         returnnewDefaultSqlSession(configuration, executor, autoCommit);  
  28.   
  29.     } catch (Exceptione) {  
  30.   
  31.        closeConnection(connection);  
  32.   
  33.         throwExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);  
  34.   
  35.     } finally {  
  36.   
  37.        ErrorContext.instance().reset();  
  38.   
  39.     }  
  40.   
  41. }  

可以看出,创建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也是动态创建的:

[java] view plain copy
  1.     public ExecutornewExecutor(Transaction transaction, ExecutorType executorType) {  
  2.   
  3.        executorType = executorType == null ? defaultExecutorType :executorType;  
  4.   
  5.        executorType = executorType == null ?ExecutorType.SIMPLE : executorType;  
  6.   
  7.         Executor executor;  
  8.   
  9.         if(ExecutorType.BATCH == executorType) {  
  10.            executor = new BatchExecutor(this,transaction);  
  11.         } elseif(ExecutorType.REUSE == executorType) {  
  12.            executor = new ReuseExecutor(this,transaction);  
  13.         } else {  
  14.             executor = newSimpleExecutor(this, transaction);  
  15.         }  
  16.   
  17.         if (cacheEnabled) {  
  18.            executor = new CachingExecutor(executor);  
  19.         }  
  20.         executor =(Executor) interceptorChain.pluginAll(executor);  
  21.         return executor;  
  22. }  


可以看出,如果不开启cache的话,创建的Executor只是3中基础类型之一,BatchExecutor专门用于执行批量sql操作,ReuseExecutor会重用statement执行sql操作,SimpleExecutor只是简单执行sql没有什么特别的。开启cache的话(默认是开启的并且没有任何理由去关闭它),就会创建CachingExecutor,它以前面创建的Executor作为唯一参数。CachingExecutor在查询数据库前先查找缓存,若没找到的话调用delegate(就是构造时传入的Executor对象)从数据库查询,并将查询结果存入缓存中。

Executor对象是可以被插件拦截的,如果定义了针对Executor类型的插件,最终生成的Executor对象是被各个插件插入后的代理对象(关于插件会有后续章节专门介绍,敬请期待)。

Mapper

Mybatis官方手册建议通过mapper对象访问mybatis,因为使用mapper看起来更优雅,就像下面这样:

[java] view plain copy
  1. session = sqlSessionFactory.openSession();  
  2. UserDao userDao= session.getMapper(UserDao.class);  
  3. UserDto user =new UserDto();  
  4. user.setUsername("iMbatis");  
  5. user.setPassword("iMbatis");  
  6. userDao.insertUser(user);  

那么这个mapper到底是什么呢,它是如何创建的呢,它又是怎么与sqlsession等关联起来的呢?下面为你一一解答。

创建

表面上看mapper是在sqlsession里创建的,但实际创建它的地方是MapperRegistry

[java] view plain copy
  1. public <T>T getMapper(Class<T> type, SqlSession sqlSession) {  
  2.     if (!knownMappers.contains(type))  
  3.         thrownewBindingException("Type " + type + " isnot known to the MapperRegistry.");  
  4.     try {  
  5.         returnMapperProxy.newMapperProxy(type, sqlSession);  
  6.     } catch (Exceptione) {  
  7.         thrownewBindingException("Error getting mapper instance. Cause: " + e, e);  
  8.     }  
  9. }  

可以看到,mapper是一个代理对象,它实现的接口就是传入的type,这就是为什么mapper对象可以通过接口直接访问。同时还可以看到,创建mapper代理对象时传入了sqlsession对象,这样就把sqlsession也关联起来了。我们进一步看看MapperProxy.newMapperProxy(type,sqlSession);背后发生了什么事情:

[java] view plain copy
  1. publicstatic <T>T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {  
  2.     ClassLoaderclassLoader = mapperInterface.getClassLoader();  
  3.     Class<?>[] interfaces = new Class[]{mapperInterface};  
  4.     MapperProxyproxy = new MapperProxy(sqlSession);  
  5.     return (T) Proxy.newProxyInstance(classLoader,interfaces, proxy);  
  6. }  

看起来没什么特别的,和其他代理类的创建一样,我们重点关注一下MapperProxyinvoke方法

MapperProxy的invoke

我们知道对被代理对象的方法的访问都会落实到代理者的invoke上来,MapperProxyinvoke如下:

[java] view plain copy
  1. public Objectinvoke(Object proxy, Method method, Object[] args) throws Throwable{  
  2.     if (method.getDeclaringClass()== Object.class) {  
  3.         return method.invoke(this, args);  
  4.     }  
  5.   
  6.     finalClass<?> declaringInterface = findDeclaringInterface(proxy, method);  
  7.     finalMapperMethod mapperMethod = newMapperMethod(declaringInterface, method, sqlSession);  
  8.     final Objectresult = mapperMethod.execute(args);  
  9.   
  10.     if (result ==null && method.getReturnType().isPrimitive()&& !method.getReturnType().equals(Void.TYPE)) {  
  11.         thrownewBindingException("Mapper method '" + method.getName() + "'(" + method.getDeclaringClass()  
  12.                 + ") attempted toreturn null from a method with a primitive return type ("  
  13.                + method.getReturnType() + ").");  
  14.     }  
  15.     return result;  
  16. }  


可以看到invoke把执行权转交给了MapperMethod,我们来看看MapperMethod里又是怎么运作的:

[java] view plain copy
  1.     public Objectexecute(Object[] args) {  
  2.         Objectresult = null;  
  3.         if(SqlCommandType.INSERT == type) {  
  4.             Objectparam = getParam(args);  
  5.             result= sqlSession.insert(commandName, param);  
  6.         } elseif(SqlCommandType.UPDATE == type) {  
  7.             Object param = getParam(args);  
  8.             result= sqlSession.update(commandName, param);  
  9.         } elseif(SqlCommandType.DELETE == type) {  
  10.             Objectparam = getParam(args);  
  11.             result= sqlSession.delete(commandName, param);  
  12.         } elseif(SqlCommandType.SELECT == type) {  
  13.             if (returnsVoid &&resultHandlerIndex != null) {  
  14.                executeWithResultHandler(args);  
  15.             } elseif (returnsList) {  
  16.                result = executeForList(args);  
  17.             } elseif (returnsMap) {  
  18.                result = executeForMap(args);  
  19.             } else {  
  20.                Object param = getParam(args);  
  21.                result = sqlSession.selectOne(commandName, param);  
  22.             }  
  23.         } else {  
  24.             thrownewBindingException("Unknown execution method for: " + commandName);  
  25.         }  
  26.         return result;  
  27.   
  28. }  


可以看到,MapperMethod就像是一个分发者,他根据参数和返回值类型选择不同的sqlsession方法来执行。这样mapper对象与sqlsession就真正的关联起来了。

Executor

前面提到过,sqlsession只是一个门面,真正发挥作用的是executor,对sqlsession方法的访问最终都会落到executor的相应方法上去。Executor分成两大类,一类是CacheExecutor,另一类是普通ExecutorExecutor的创建前面已经介绍了,下面介绍下他们的功能:

CacheExecutor

CacheExecutor有一个重要属性delegate,它保存的是某类普通的Executor,值在构照时传入。执行数据库update操作时,它直接调用delegateupdate方法,执行query方法时先尝试从cache中取值,取不到再调用delegate的查询方法,并将查询结果存入cache中。代码如下:

[java] view plain copy
  1. public Listquery(MappedStatement ms, Object parameterObject, RowBounds rowBounds,ResultHandler resultHandler) throws SQLException {  
  2.     if (ms != null) {  
  3.         Cachecache = ms.getCache();  
  4.         if (cache != null) {  
  5.            flushCacheIfRequired(ms);  
  6.            cache.getReadWriteLock().readLock().lock();  
  7.            try {  
  8.                if (ms.isUseCache() && resultHandler ==null) {  
  9.                    CacheKey key = createCacheKey(ms, parameterObject, rowBounds);  
  10.                    final List cachedList = (List)cache.getObject(key);  
  11.                    if (cachedList != null) {  
  12.                         returncachedList;  
  13.                    } else {  
  14.                        List list = delegate.query(ms,parameterObject, rowBounds, resultHandler);  
  15.                        tcm.putObject(cache,key, list);  
  16.                        return list;  
  17.                    }  
  18.                } else {  
  19.                    returndelegate.query(ms,parameterObject, rowBounds, resultHandler);  
  20.                }  
  21.             } finally {  
  22.                cache.getReadWriteLock().readLock().unlock();  
  23.             }  
  24.         }  
  25.     }  
  26.     returndelegate.query(ms,parameterObject, rowBounds, resultHandler);  
  27. }  

普通Executor

普通Executor3类,他们都继承于BaseExecutorBatchExecutor专门用于执行批量sql操作,ReuseExecutor会重用statement执行sql操作,SimpleExecutor只是简单执行sql没有什么特别的。下面以SimpleExecutor为例:

[java] view plain copy
  1. public ListdoQuery(MappedStatement ms, Object parameter, RowBounds rowBounds,ResultHandler resultHandler) throws SQLException {  
  2.     Statementstmt = null;  
  3.     try {  
  4.        Configuration configuration = ms.getConfiguration();  
  5.        StatementHandler handler = configuration.newStatementHandler(this, ms,parameter, rowBounds,resultHandler);  
  6.        stmt =prepareStatement(handler);  
  7.        returnhandler.query(stmt, resultHandler);  
  8.     } finally {  
  9.        closeStatement(stmt);  
  10.     }  
  11. }  

可以看出,Executor本质上也是个甩手掌柜,具体的事情原来是StatementHandler来完成的。

StatementHandler

Executor将指挥棒交给StatementHandler后,接下来的工作就是StatementHandler的事了。我们先看看StatementHandler是如何创建的。

创建

[java] view plain copy
  1. publicStatementHandler newStatementHandler(Executor executor, MappedStatementmappedStatement,  
  2.         ObjectparameterObject, RowBounds rowBounds, ResultHandler resultHandler) {  
  3.    StatementHandler statementHandler = newRoutingStatementHandler(executor, mappedStatement,parameterObject,rowBounds, resultHandler);  
  4.    statementHandler= (StatementHandler) interceptorChain.pluginAll(statementHandler);  
  5.    returnstatementHandler;  
  6. }  

可以看到每次创建的StatementHandler都是RoutingStatementHandler,它只是一个分发者,他一个属性delegate用于指定用哪种具体的StatementHandler。可选的StatementHandlerSimpleStatementHandlerPreparedStatementHandlerCallableStatementHandler三种。选用哪种在mapper配置文件的每个statement里指定,默认的是PreparedStatementHandler。同时还要注意到StatementHandler是可以被拦截器拦截的,和Executor一样,被拦截器拦截后的对像是一个代理对象。由于mybatis没有实现数据库的物理分页,众多物理分页的实现都是在这个地方使用拦截器实现的,本文作者也实现了一个分页拦截器,在后续的章节会分享给大家,敬请期待。

初始化

StatementHandler创建后需要执行一些初始操作,比如statement的开启和参数设置、对于PreparedStatement还需要执行参数的设置操作等。代码如下:

[java] view plain copy
  1. private StatementprepareStatement(StatementHandler handler) throwsSQLException {  
  2.     Statementstmt;  
  3.     Connectionconnection = transaction.getConnection();  
  4.     stmt =handler.prepare(connection);  
  5.     handler.parameterize(stmt);  
  6.     return stmt;  
  7. }  

statement的开启和参数设置没什么特别的地方,handler.parameterize倒是可以看看是怎么回事。handler.parameterize通过调用ParameterHandlersetParameters完成参数的设置,ParameterHandler随着StatementHandler的创建而创建,默认的实现是DefaultParameterHandler

[java] view plain copy
  1. publicParameterHandler newParameterHandler(MappedStatement mappedStatement, ObjectparameterObject, BoundSql boundSql) {  
  2.    ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,parameterObject,boundSql);  
  3.    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);  
  4.    returnparameterHandler;  
  5. }  

ExecutorStatementHandler一样,ParameterHandler也是可以被拦截的。

参数设置

DefaultParameterHandler里设置参数的代码如下:

[java] view plain copy
  1. publicvoidsetParameters(PreparedStatement ps) throwsSQLException {  
  2.    ErrorContext.instance().activity("settingparameters").object(mappedStatement.getParameterMap().getId());  
  3.    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();  
  4.     if(parameterMappings != null) {  
  5.        MetaObject metaObject = parameterObject == null ? null :configuration.newMetaObject(parameterObject);  
  6.         for (int i = 0; i< parameterMappings.size(); i++) {  
  7.            ParameterMapping parameterMapping = parameterMappings.get(i);  
  8.             if(parameterMapping.getMode() != ParameterMode.OUT) {  
  9.                Object value;  
  10.                String propertyName = parameterMapping.getProperty();  
  11.                PropertyTokenizer prop = newPropertyTokenizer(propertyName);  
  12.                if (parameterObject == null) {  
  13.                    value = null;  
  14.                } elseif (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){  
  15.                    value = parameterObject;  
  16.                } elseif (boundSql.hasAdditionalParameter(propertyName)){  
  17.                    value = boundSql.getAdditionalParameter(propertyName);  
  18.                } elseif(propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)  
  19.                         && boundSql.hasAdditionalParameter(prop.getName())){  
  20.                    value = boundSql.getAdditionalParameter(prop.getName());  
  21.                    if (value != null) {  
  22.                         value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));  
  23.                    }  
  24.                } else {  
  25.                    value = metaObject == null ? null :metaObject.getValue(propertyName);  
  26.                }  
  27.                TypeHandler typeHandler = parameterMapping.getTypeHandler();  
  28.                if (typeHandler == null) {  
  29.                    thrownew ExecutorException("Therewas no TypeHandler found for parameter " + propertyName  + " of statement " + mappedStatement.getId());  
  30.                 }  
  31.                typeHandler.setParameter(ps, i + 1, value,parameterMapping.getJdbcType());  
  32.             }  
  33.   
  34.         }  
  35.   
  36.     }  
  37. }  

这里面最重要的一句其实就是最后一句代码,它的作用是用合适的TypeHandler完成参数的设置。那么什么是合适的TypeHandler呢,它又是如何决断出来的呢?BaseStatementHandler的构造方法里有这么一句:

this.boundSql= mappedStatement.getBoundSql(parameterObject);

它触发了sql 的解析,在解析sql的过程中,TypeHandler也被决断出来了,决断的原则就是根据参数的类型和参数对应的JDBC类型决定使用哪个TypeHandler。比如:参数类型是String的话就用StringTypeHandler,参数类型是整数的话就用IntegerTypeHandler等

参数设置完毕后,执行数据库操作(update或query)。如果是query最后还有个查询结果的处理过程。

结果处理

结果处理使用ResultSetHandler来完成,默认的ResultSetHandler是FastResultSetHandler,它在创建StatementHandler时一起创建,代码如下

[java] view plain copy
  1. publicResultSetHandler newResultSetHandler(Executor executor, MappedStatementmappedStatement,  
  2. RowBoundsrowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSqlboundSql) {  
  3.    ResultSetHandler resultSetHandler =mappedStatement.hasNestedResultMaps() ? newNestedResultSetHandler(executor, mappedStatement, parameterHandler,resultHandler, boundSql, rowBounds): new FastResultSetHandler(executor,mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);  
  4.    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);  
  5.    returnresultSetHandler;  
  6. }  

可以看出ResultSetHandler也是可以被拦截的,可以编写自己的拦截器改变ResultSetHandler的默认行为。

[java] view plain copy
  1. ResultSetHandler内部一条记录一条记录的处理,在处理每条记录的每一列时会调用TypeHandler转换结果,如下:  
  2.   
  3.     protectedbooleanapplyAutomaticMappings(ResultSet rs, List<String> unmappedColumnNames,MetaObject metaObject) throws SQLException {  
  4.         booleanfoundValues = false;  
  5.         for (StringcolumnName : unmappedColumnNames) {  
  6.             final Stringproperty = metaObject.findProperty(columnName);  
  7.             if (property!= null) {  
  8.                 final ClasspropertyType =metaObject.getSetterType(property);  
  9.                 if (typeHandlerRegistry.hasTypeHandler(propertyType)) {  
  10.                    final TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(propertyType);  
  11.                    final Object value = typeHandler.getResult(rs,columnName);  
  12.                    if (value != null) {  
  13.                        metaObject.setValue(property, value);  
  14.                        foundValues = true;  
  15.                    }  
  16.                 }  
  17.             }  
  18.         }  
  19.         returnfoundValues;  
  20.    }  

从代码里可以看到,决断TypeHandler使用的是结果参数的属性类型。因此我们在定义作为结果的对象的属性时一定要考虑与数据库字段类型的兼容性。


0 0
原创粉丝点击