千家信息网

MyBatis之SqlSession介绍

发表于:2024-11-17 作者:千家信息网编辑
千家信息网最后更新 2024年11月17日,鲁春利的工作笔记,好记性不如烂笔头转载自:深入浅出MyBatis-SqlsessionSqlSession的创建Sqlsession对应着一次数据库会话。由于数据库回话不是永久的,因此Sqlsessi
千家信息网最后更新 2024年11月17日MyBatis之SqlSession介绍

鲁春利的工作笔记,好记性不如烂笔头



转载自:深入浅出MyBatis-Sqlsession


SqlSession的创建

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

package org.apache.ibatis.session;import java.sql.Connection;public interface SqlSessionFactory {  SqlSession openSession();  SqlSession openSession(boolean autoCommit);  SqlSession openSession(Connection connection);  SqlSession openSession(TransactionIsolationLevel level);  SqlSession openSession(ExecutorType execType);  SqlSession openSession(ExecutorType execType, boolean autoCommit);  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);  SqlSession openSession(ExecutorType execType, Connection connection);  Configuration getConfiguration();}

实际创建SqlSession的地方是openSessionFromDataSource,如下:

package org.apache.ibatis.session.defaults;import java.sql.Connection;import java.sql.SQLException;import org.apache.ibatis.exceptions.ExceptionFactory;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.Environment;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.ExecutorType;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.TransactionIsolationLevel;import org.apache.ibatis.transaction.Transaction;import org.apache.ibatis.transaction.TransactionFactory;import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;public class DefaultSqlSessionFactory implements SqlSessionFactory {  private final Configuration configuration;  public DefaultSqlSessionFactory(Configuration configuration) {    this.configuration = configuration;  }  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, autoCommit);      return new DefaultSqlSession(configuration, executor);    } 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();    }  }}

可以看出,创建sqlsession经过了以下几个主要步骤:

1) 从配置中获取Environment

2)Environment中取得DataSource

3)Environment中取得TransactionFactory

4) DataSource里获取数据库连接对象Connection

5) 在取得的数据库连接上创建事务对象Transaction

6) 创建Executor对象(该对象非常重要,事实上sqlsession的所有操作都是通过它完成的);

7) 创建sqlsession对象。


Executor的创建

Sqlsession只是个门面,真正干事的是Executor,Sqlsession对数据库的操作都是通过Executor来完成的。与Sqlsession一样,Executor也是动态创建的:

final Executor executor = configuration.newExecutor(tx, execType, autoCommit);

Configuration类的实现:

public class Configuration {  protected Environment environment;    public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {    executorType = executorType == null ? defaultExecutorType : executorType;    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;    Executor executor;    if (ExecutorType.BATCH == executorType) {      executor = new BatchExecutor(this, transaction);    } else if (ExecutorType.REUSE == executorType) {      executor = new ReuseExecutor(this, transaction);    } else {      executor = new SimpleExecutor(this, transaction);    }    if (cacheEnabled) {      executor = new CachingExecutor(executor, autoCommit);    }    executor = (Executor) interceptorChain.pluginAll(executor);    return executor;  } }

Executor的定义:

package org.apache.ibatis.executor;import java.sql.SQLException;import java.util.List;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.transaction.Transaction;public interface Executor {  ResultHandler NO_RESULT_HANDLER = null;  int update(MappedStatement ms, Object parameter) throws SQLException;   List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql) throws SQLException;   List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException;  List flushStatements() throws SQLException;  void commit(boolean required) throws SQLException;  void rollback(boolean required) throws SQLException;  CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);  boolean isCached(MappedStatement ms, CacheKey key);  void clearLocalCache();  void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class targetType);  Transaction getTransaction();  void close(boolean forceRollback);  boolean isClosed();}

可以看出,创建的Executor只是3中基础类型之一:

BatchExecutor专门用于执行批量sql操作

ReuseExecutor会重用statement执行sql操作

SimpleExecutor只是简单执行sql没有什么特别的。

如果开启cache的话(默认是开启的并且没有任何理由去关闭它),就会创建CachingExecutor,它以前面创建的Executor作为唯一参数。CachingExecutor在查询数据库前先查找缓存,若没找到的话调用delegate(就是构造时传入的Executor对象)从数据库查询,并将查询结果存入缓存中。

package org.apache.ibatis.executor;import java.sql.SQLException;import java.util.List;import org.apache.ibatis.cache.Cache;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.cache.TransactionalCacheManager;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.ParameterMapping;import org.apache.ibatis.mapping.ParameterMode;import org.apache.ibatis.mapping.StatementType;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.transaction.Transaction;public class CachingExecutor implements Executor {  private Executor delegate;  private boolean autoCommit; // issue #573. No need to call commit() on autoCommit sessions  private TransactionalCacheManager tcm = new TransactionalCacheManager();  private boolean dirty;  public CachingExecutor(Executor delegate) {    this(delegate, false);  }  public CachingExecutor(Executor delegate, boolean autoCommit) {    this.delegate = delegate;    this.autoCommit = autoCommit;  }  public Transaction getTransaction() {    return delegate.getTransaction();  }  public void close(boolean forceRollback) {    try {      //issue #499. Unresolved session handling      //issue #573. Autocommit sessions should commit      if (dirty && !autoCommit) {         tcm.rollback();      } else {        tcm.commit();      }    } finally {      delegate.close(forceRollback);    }  }    // 其他代码略    }

Executor对象是可以被插件拦截的(拦截器Interceptor,如:

@Intercepts({@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})

),如果定义了针对Executor类型的插件,最终生成的Executor对象是被各个插件插入后的代理对象。


Mapper介绍

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

session = sqlSessionFactory.openSession();  UserMapper userMapper= session.getMapper(UserMapper.class);  UserBo user = new UserBo();  user.setUsername("iMbatis");  user.setPassword("iMbatis");  userMapper.insertUser(user);

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

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

package org.apache.ibatis.session;import java.io.Closeable;import java.sql.Connection;import java.util.List;import java.util.Map;import org.apache.ibatis.executor.BatchResult;/** * The primary Java interface for working with MyBatis. * Through this interface you can execute commands, get mappers and manage transactions. * */public interface SqlSession extends Closeable {   T selectOne(String statement);   T selectOne(String statement, Object parameter);   List selectList(String statement);   List selectList(String statement, Object parameter);   List selectList(String statement, Object parameter, RowBounds rowBounds);   Map selectMap(String statement, String mapKey);   Map selectMap(String statement, Object parameter, String mapKey);   Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);  void select(String statement, Object parameter, ResultHandler handler);  void select(String statement, ResultHandler handler);  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);  int insert(String statement);  int insert(String statement, Object parameter);  int update(String statement);  int update(String statement, Object parameter);  int delete(String statement);  int delete(String statement, Object parameter);  void commit();  void commit(boolean force);  void rollback();  void rollback(boolean force);  List flushStatements();  void close();  void clearCache();  Configuration getConfiguration();   T getMapper(Class type);  Connection getConnection();}

SqlSeesion是接口,getMapper肯定是通过起实现类来完成的,查看其类结构:

package org.apache.ibatis.session.defaults;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.session.SqlSession;public class DefaultSqlSession implements SqlSession {  private Configuration configuration;  private Executor executor;  private boolean dirty;      public  T getMapper(Class type) {    return configuration.getMapper(type, this);  }}  -- 其中configuration的实现为  public  T getMapper(Class type, SqlSession sqlSession) {    return mapperRegistry.getMapper(type, sqlSession);  }  -- MapperRegistry的实现为package org.apache.ibatis.binding;public class MapperRegistry {  private Configuration config;  private final Map, MapperProxyFactory> knownMappers = new HashMap, MapperProxyFactory>();  public MapperRegistry(Configuration config) {    this.config = config;  }    @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  boolean hasMapper(Class type) {        return knownMappers.containsKey(type);    }    public  void addMapper(Class type) {     if (type.isInterface()) {      if (hasMapper(type)) {        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");      }      boolean loadCompleted = false;      try {        knownMappers.put(type, new MapperProxyFactory(type));        // It's important that the type is added before the parser is run        // otherwise the binding may automatically be attempted by the        // mapper parser. If the type is already known, it won't try.        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);        parser.parse();        loadCompleted = true;      } finally {        if (!loadCompleted) {          knownMappers.remove(type);        }      }    }}

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

package org.apache.ibatis.binding;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import org.apache.ibatis.session.SqlSession;public class MapperProxyFactory {  private final Class mapperInterface;  private Map methodCache = new ConcurrentHashMap();  public MapperProxyFactory(Class mapperInterface) {    this.mapperInterface = mapperInterface;  }  public Class getMapperInterface() {    return mapperInterface;  }  public Map getMethodCache() {    return methodCache;  }   /**    * newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h)    *   ClassLoader loader :类加载器,一般使用和被代理对象相同的类加载器    *   Class[] interfaces :被代理对象(目标对象)的接口数组    *   InvocationHandler h : 设置回调对象,当代理对象的方法被调用时,会委派给该参数指定对象的invoke方法     */  @SuppressWarnings("unchecked")  protected T newInstance(MapperProxy mapperProxy) {    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);  }  public T newInstance(SqlSession sqlSession) {    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);    return newInstance(mapperProxy);  }}

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

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

package org.apache.ibatis.binding;import java.io.Serializable;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.util.Map;import org.apache.ibatis.reflection.ExceptionUtil;import org.apache.ibatis.session.SqlSession;/** * @author Clinton Begin * @author Eduardo Macarron */public class MapperProxy implements InvocationHandler, Serializable {  private static final long serialVersionUID = -6424540398559729838L;  private final SqlSession sqlSession;  private final Class mapperInterface;  private final Map methodCache;  public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {    this.sqlSession = sqlSession;    this.mapperInterface = mapperInterface;    this.methodCache = methodCache;  }  @Override  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    if (Object.class.equals(method.getDeclaringClass())) {      try {        // 转调具体目标对象的方法,这里目标对象为this        return method.invoke(this, args);      } catch (Throwable t) {        throw ExceptionUtil.unwrapThrowable(t);      }    }    final MapperMethod mapperMethod = cachedMapperMethod(method);    return mapperMethod.execute(sqlSession, args);  }  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;  }}

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

package org.apache.ibatis.binding;import org.apache.ibatis.annotations.Flush;import org.apache.ibatis.annotations.MapKey;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.SqlCommandType;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.session.SqlSession;import java.lang.reflect.Array;import java.lang.reflect.Method;import java.util.*;/** * @author Clinton Begin * @author Eduardo Macarron * @author Lasse Voss */public class MapperMethod {  private final SqlCommand command;  private final MethodSignature method;  public MapperMethod(Class mapperInterface, Method method, Configuration config) {    this.command = new SqlCommand(config, mapperInterface, method);    this.method = new MethodSignature(config, method);  }  public Object execute(SqlSession sqlSession, Object[] args) {    Object result;    if (SqlCommandType.INSERT == command.getType()) {      Object param = method.convertArgsToSqlCommandParam(args);      result = rowCountResult(sqlSession.insert(command.getName(), param));    } else if (SqlCommandType.UPDATE == command.getType()) {      Object param = method.convertArgsToSqlCommandParam(args);      result = rowCountResult(sqlSession.update(command.getName(), param));    } else if (SqlCommandType.DELETE == command.getType()) {      Object param = method.convertArgsToSqlCommandParam(args);      result = rowCountResult(sqlSession.delete(command.getName(), param));    } else if (SqlCommandType.SELECT == command.getType()) {      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 {        Object param = method.convertArgsToSqlCommandParam(args);        result = sqlSession.selectOne(command.getName(), param);      }    } else if (SqlCommandType.FLUSH == command.getType()) {        result = sqlSession.flushStatements();    } else {      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;  }}

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


Executor介绍

sqlsession只是一个门面,真正发挥作用的是executor,对sqlsession方法的访问最终都会落到executor的相应方法上去

Executor分成两大类:一类是CacheExecutor,另一类是普通Executor

CacheExecutor

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

  @Override  public  List 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, parameterObject, boundSql);        @SuppressWarnings("unchecked")        List list = (List) tcm.getObject(cache, key);        if (list == null) {          list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);          tcm.putObject(cache, key, list); // issue #578 and #116        }        return list;      }    }     // delegate.query实际是org.apache.ibatis.executor.BaseExecutor.query     // 最终会调用BaseExecutor     return delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);  }

普通Executor

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

  @Override  public  List doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {    Statement stmt = null;    try {      Configuration configuration = ms.getConfiguration();      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);      stmt = prepareStatement(handler, ms.getStatementLog());      return handler.query(stmt, resultHandler);    } finally {      closeStatement(stmt);    }  }

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


StatementHandler介绍

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

StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);

configuration.newStatementHandler的实现为:

  public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);    return statementHandler;  }

可以看到每次创建的StatementHandler都是RoutingStatementHandler,它只是一个分发者,他一个属性delegate用于指定用哪种具体的StatementHandler


同时还要注意到StatementHandler是可以被拦截器拦截的,和Executor一样,被拦截器拦截后的对像是一个代理对象。由于mybatis没有实现数据库的物理分页,众多物理分页的实现都是在这个地方使用拦截器实现的


可选的StatementHandler有SimpleStatementHandler、PreparedStatementHandler和CallableStatementHandler三种。选用哪种在mapper配置文件的每个statement里指定,默认的是PreparedStatementHandler


statementType的取值是通过DTD文件来约束的:

详见:http://mybatis.org/dtd/mybatis-3-mapper.dtd

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

代码如下:org.apache.ibatis.executor.SimpleExecutor

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {    Statement stmt;    Connection connection = getConnection(statementLog);    stmt = handler.prepare(connection);    handler.parameterize(stmt);    return stmt;  }



statement的开启和参数设置没什么特别的地方:

package org.apache.ibatis.executor.statement;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.executor.ExecutorException;import org.apache.ibatis.executor.parameter.ParameterHandler;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;/** * @author Clinton Begin */public class RoutingStatementHandler implements StatementHandler {  private final StatementHandler delegate;  public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {    switch (ms.getStatementType()) {      case STATEMENT:        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);        break;      case PREPARED:        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);        break;      case CALLABLE:        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);        break;      default:        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());    }  }  @Override  public Statement prepare(Connection connection) throws SQLException {    return delegate.prepare(connection);  }}

org.apache.ibatis.executor.statement.PreparedStatementHandler并没有对prepare的具体实现,调用的还是其父类org.apache.ibatis.executor.statement.BaseStatementHandler的实现:

  @Override  public Statement prepare(Connection connection) throws SQLException {    ErrorContext.instance().sql(boundSql.getSql());    Statement statement = null;    try {      statement = instantiateStatement(connection);      setStatementTimeout(statement);      setFetchSize(statement);      return statement;    } catch (SQLException e) {      closeStatement(statement);      throw e;    } catch (Exception e) {      closeStatement(statement);      throw new ExecutorException("Error preparing statement.  Cause: " + e, e);    }  }

handler.parameterize倒是可以看看是怎么回事

handler.parameterize通过调用ParameterHandlersetParameters完成参数的设置,ParameterHandler随着StatementHandler的创建而创建,默认的实现是DefaultParameterHandler

// ======================================================================package org.apache.ibatis.executor.statement;/** * @author Clinton Begin */public class PreparedStatementHandler extends BaseStatementHandler {  public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {    super(executor, mappedStatement, parameter, rowBounds, resultHandler, boundSql);  }  // 代码略  @Override  public void parameterize(Statement statement) throws SQLException {    parameterHandler.setParameters((PreparedStatement) statement);  }}// ======================================================================package org.apache.ibatis.executor.statement;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.executor.ExecutorException;import org.apache.ibatis.executor.keygen.KeyGenerator;import org.apache.ibatis.executor.parameter.ParameterHandler;import org.apache.ibatis.executor.resultset.ResultSetHandler;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.reflection.factory.ObjectFactory;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.type.TypeHandlerRegistry;/** * @author Clinton Begin */public abstract class BaseStatementHandler implements StatementHandler {  protected final Configuration configuration;  protected final ObjectFactory objectFactory;  protected final TypeHandlerRegistry typeHandlerRegistry;  protected final ResultSetHandler resultSetHandler;  protected final ParameterHandler parameterHandler;  protected final Executor executor;  protected final MappedStatement mappedStatement;  protected final RowBounds rowBounds;  protected BoundSql boundSql;  protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {    this.configuration = mappedStatement.getConfiguration();    this.executor = executor;    this.mappedStatement = mappedStatement;    this.rowBounds = rowBounds;    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();    this.objectFactory = configuration.getObjectFactory();    if (boundSql == null) { // issue #435, get the key before calculating the statement      generateKeys(parameterObject);      boundSql = mappedStatement.getBoundSql(parameterObject);    }    this.boundSql = boundSql;        // 默认为org.apache.ibatis.scripting.defaults.DefaultParameterHandler    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);  }}


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


DefaultParameterHandler

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

package org.apache.ibatis.scripting.defaults;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.List;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.executor.parameter.ParameterHandler;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.ParameterMapping;import org.apache.ibatis.mapping.ParameterMode;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.type.JdbcType;import org.apache.ibatis.type.TypeException;import org.apache.ibatis.type.TypeHandler;import org.apache.ibatis.type.TypeHandlerRegistry;/** * @author Clinton Begin * @author Eduardo Macarron */public class DefaultParameterHandler implements ParameterHandler {  private final TypeHandlerRegistry typeHandlerRegistry;  private final MappedStatement mappedStatement;  private final Object parameterObject;  private BoundSql boundSql;  private Configuration configuration;  public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {    this.mappedStatement = mappedStatement;    this.configuration = mappedStatement.getConfiguration();    this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();    this.parameterObject = parameterObject;    this.boundSql = boundSql;  }  @Override  public Object getParameterObject() {    return parameterObject;  }  @Override  public void setParameters(PreparedStatement ps) {    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());    List parameterMappings = boundSql.getParameterMappings();    if (parameterMappings != null) {      for (int i = 0; i < parameterMappings.size(); i++) {        ParameterMapping parameterMapping = parameterMappings.get(i);        if (parameterMapping.getMode() != ParameterMode.OUT) {          Object value;          String propertyName = parameterMapping.getProperty();          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params            value = boundSql.getAdditionalParameter(propertyName);          } else if (parameterObject == null) {            value = null;          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {            value = parameterObject;          } else {            MetaObject metaObject = configuration.newMetaObject(parameterObject);            value = metaObject.getValue(propertyName);          }          TypeHandler typeHandler = parameterMapping.getTypeHandler();          JdbcType jdbcType = parameterMapping.getJdbcType();          if (value == null && jdbcType == null) {            jdbcType = configuration.getJdbcTypeForNull();          }          try {            typeHandler.setParameter(ps, i + 1, value, jdbcType);          } catch (TypeException e) {            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);          } catch (SQLException e) {            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);          }        }      }    }  }}

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

    if (boundSql == null) { // issue #435, get the key before calculating the statement      generateKeys(parameterObject);      boundSql = mappedStatement.getBoundSql(parameterObject);    }

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

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


ResultSetHandler

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

org.apache.ibatis.executor.statement.BaseStatementHandler

    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);

org.apache.ibatis.session.Configuration

  public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,      ResultHandler resultHandler, BoundSql boundSql) {    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);    return resultSetHandler;  }

org.apache.ibatis.executor.statement.PreparedStatementHandler

  @Override  public  List query(Statement statement, ResultHandler resultHandler) throws SQLException {    PreparedStatement ps = (PreparedStatement) statement;    ps.execute();    return resultSetHandler. handleResultSets(ps);  }

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


  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {    List autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);    boolean foundValues = false;    if (autoMapping.size() > 0) {      for (UnMappedColumAutoMapping mapping : autoMapping) {        final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);        // issue #377, call setter on nulls        if (value != null || configuration.isCallSettersOnNulls()) {          if (value != null || !mapping.primitive) {            metaObject.setValue(mapping.property, value);          }          foundValues = true;        }      }    }    return foundValues;  }

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



附件:http://down.51cto.com/data/2366409
对象 参数 方法 数据 数据库 代理 类型 代码 就是 只是 结果 查询 地方 拦截器 普通 决断 属性 接口 重要 又是 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 芜湖软件开发技术项目实训中心 计算机三级网络技术分数分配 石家庄网络安全宣传 贵阳市网络安全办公室 软件开发如何使用 数据库null值怎么yes 中山戴尔服务器报价 关于国家对网络安全的制度 服务器往外倒文件 中国互联网科技对比 数据库连接20分钟后会自动断开 福建专业软件开发费用 软件开发有哪些兼职 开州区税务局网络安全工作 数据库表格转excel 网络技术经销商又称为A 58同城服务器连接超时 广东软件开发学校 数据库实现与系统实现是什么 明日之后最受欢迎的服务器是什么 广东erp软件开发报价 南京尚尔网络技术有限公司 浙江好的软件开发创新服务 定西邮储银行网络安全 oracle数据库显示冷僻字 我的世界服务器一键 硬件维护在网络安全中的作用 检索中文期刊论文用哪几个数据库 明确保障网络安全的基本目标 服务器安装后怎么显示无响应
0