千家信息网

Mybatis源码分析[04.SqlSession]

发表于:2025-01-27 作者:千家信息网编辑
千家信息网最后更新 2025年01月27日,/** * 这是MyBatis用来执行SQL的类,获取映射器,管理事务 * */public interface SqlSession extends Closeable { /** * Ret
千家信息网最后更新 2025年01月27日Mybatis源码分析[04.SqlSession]
/** * 这是MyBatis用来执行SQL的类,获取映射器,管理事务 * */public interface SqlSession extends Closeable {  /**   * Retrieve a single row mapped from the statement key   * 根据指定的SqlID获取一条记录的封装对象   * @param  the returned object type 封装之后的对象类型   * @param statement sqlID   * @return Mapped object 封装之后的对象   */   T selectOne(String statement);  /**   * Retrieve a single row mapped from the statement key and parameter.   * 根据指定的SqlID获取一条记录的封装对象,只不过这个方法容许我们可以给sql传递一些参数   * 一般在实际使用中,这个参数传递的是pojo,或者Map或者ImmutableMap   * @param  the returned object type   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @return Mapped object   */   T selectOne(String statement, Object parameter);  /**   * Retrieve a list of mapped objects from the statement key and parameter.   * 根据指定的sqlId获取多条记录   * @param  the returned list element type   * @param statement Unique identifier matching the statement to use.   * @return List of mapped object   */   List selectList(String statement);  /**   * Retrieve a list of mapped objects from the statement key and parameter.   * 获取多条记录,这个方法容许我们可以传递一些参数   * @param  the returned list element type   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @return List of mapped object   */   List selectList(String statement, Object parameter);  /**   * Retrieve a list of mapped objects from the statement key and parameter,   * within the specified row bounds.   * 获取多条记录,这个方法容许我们可以传递一些参数,不过这个方法容许我们进行   * 分页查询。   *   * 需要注意的是默认情况下,Mybatis为了扩展性,仅仅支持内存分页。也就是会先把   * 所有的数据查询出来以后,然后在内存中进行分页。因此在实际的情况中,需要注意   * 这一点。   *   * @param  the returned list element type   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @param rowBounds  Bounds to limit object retrieval   * @return List of mapped object   */   List selectList(String statement, Object parameter, RowBounds rowBounds);  /**   * The selectMap is a special case in that it is designed to convert a list   * of results into a Map based on one of the properties in the resulting   * objects.   * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id")   * 将查询到的结果列表转换为Map类型。   * @param  the returned Map keys type   * @param  the returned Map values type   * @param statement Unique identifier matching the statement to use.   * @param mapKey The property to use as key for each value in the list. 这个参数会作为结果map的key   * @return Map containing key pair data.   */   Map selectMap(String statement, String mapKey);  /**   * The selectMap is a special case in that it is designed to convert a list   * of results into a Map based on one of the properties in the resulting   * objects.   * 将查询到的结果列表转换为Map类型。这个方法容许我们传入需要的参数   * @param  the returned Map keys type   * @param  the returned Map values type   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @param mapKey The property to use as key for each value in the list.   * @return Map containing key pair data.   */   Map selectMap(String statement, Object parameter, String mapKey);  /**   * The selectMap is a special case in that it is designed to convert a list   * of results into a Map based on one of the properties in the resulting   * objects.   * 获取多条记录,加上分页,并存入Map   * @param  the returned Map keys type   * @param  the returned Map values type   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @param mapKey The property to use as key for each value in the list.   * @param rowBounds  Bounds to limit object retrieval   * @return Map containing key pair data.   */   Map selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);  /**   * Retrieve a single row mapped from the statement key and parameter   * using a {@code ResultHandler}.   *   * @param statement Unique identifier matching the statement to use.   * @param parameter A parameter object to pass to the statement.   * @param handler ResultHandler that will handle each retrieved row   * @return Mapped object   */  void select(String statement, Object parameter, ResultHandler handler);  /**   * Retrieve a single row mapped from the statement   * using a {@code ResultHandler}.   * 获取一条记录,并转交给ResultHandler处理。这个方法容许我们自己定义对   * 查询到的行的处理方式。   * @param statement Unique identifier matching the statement to use.   * @param handler ResultHandler that will handle each retrieved row   * @return Mapped object   */  void select(String statement, ResultHandler handler);  /**   * Retrieve a single row mapped from the statement key and parameter   * using a {@code ResultHandler} and {@code RowBounds}   * 获取一条记录,加上分页,并转交给ResultHandler处理   * @param statement Unique identifier matching the statement to use.   * @param rowBounds RowBound instance to limit the query results   * @param handler ResultHandler that will handle each retrieved row   * @return Mapped object   */  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);  /**   * Execute an insert statement.   * 插入记录。   * @param statement Unique identifier matching the statement to execute.   * @return int The number of rows affected by the insert.   */  int insert(String statement);  /**   * Execute an insert statement with the given parameter object. Any generated   * autoincrement values or selectKey entries will modify the given parameter   * object properties. Only the number of rows affected will be returned.   * 插入记录,容许传入参数。   * @param statement Unique identifier matching the statement to execute.   * @param parameter A parameter object to pass to the statement.   * @return int The number of rows affected by the insert. 注意返回的是受影响的行数   */  int insert(String statement, Object parameter);  /**   * Execute an update statement. The number of rows affected will be returned.   * 更新记录。返回的是受影响的行数   * @param statement Unique identifier matching the statement to execute.   * @return int The number of rows affected by the update.   */  int update(String statement);  /**   * Execute an update statement. The number of rows affected will be returned.   * 更新记录   * @param statement Unique identifier matching the statement to execute.   * @param parameter A parameter object to pass to the statement.   * @return int The number of rows affected by the update. 返回的是受影响的行数   */  int update(String statement, Object parameter);  /**   * Execute a delete statement. The number of rows affected will be returned.   * 删除记录   * @param statement Unique identifier matching the statement to execute.   * @return int The number of rows affected by the delete. 返回的是受影响的行数   */  int delete(String statement);  /**   * Execute a delete statement. The number of rows affected will be returned.   * 删除记录   * @param statement Unique identifier matching the statement to execute.   * @param parameter A parameter object to pass to the statement.   * @return int The number of rows affected by the delete. 返回的是受影响的行数   */  int delete(String statement, Object parameter);  //以下是事务控制方法,commit,rollback  /**   * Flushes batch statements and commits database connection.   * Note that database connection will not be committed if no updates/deletes/inserts were called.   * To force the commit call {@link SqlSession#commit(boolean)}   */  void commit();  /**   * Flushes batch statements and commits database connection.   * @param force forces connection commit   */  void commit(boolean force);  /**   * Discards pending batch statements and rolls database connection back.   * Note that database connection will not be rolled back if no updates/deletes/inserts were called.   * To force the rollback call {@link SqlSession#rollback(boolean)}   */  void rollback();  /**   * Discards pending batch statements and rolls database connection back.   * Note that database connection will not be rolled back if no updates/deletes/inserts were called.   * @param force forces connection rollback   */  void rollback(boolean force);  /**   * Flushes batch statements.   * 刷新批处理语句,返回批处理结果   * @return BatchResult list of updated records   * @since 3.0.6   */  List flushStatements();  /**   * Closes the session   * 关闭Session   */  @Override  void close();  /**   * Clears local session cache   * 清理Session缓存   */  void clearCache();  /**   * Retrieves current configuration   * 得到配置   * @return Configuration   */  Configuration getConfiguration();  /**   * Retrieves a mapper.   * 得到映射器   * 这个巧妙的使用了泛型,使得类型安全   * 到了MyBatis 3,还可以用注解,这样xml都不用写了   * @param  the mapper type   * @param type Mapper interface class   * @return a mapper bound to this SqlSession   */   T getMapper(Class type);  /**   * Retrieves inner database connection   * 得到数据库连接   * @return Connection   */  Connection getConnection();}

SqlSession是一个接口类,其实际实现类为DefaultSqlSession

// DefaultSqlSession属性public class DefaultSqlSession implements SqlSession {  private Configuration configuration;  private Executor executor;  /**   * 是否自动提交   */  private boolean autoCommit;  private boolean dirty;}

DefaultSqlSession最为关键的是Executor executor,Executor为一个接口类,DefaultSqlSession对外提供的接口,内部均调用Executor executor.

public interface Executor {  //不需要ResultHandler  ResultHandler NO_RESULT_HANDLER = null;  //更新  int update(MappedStatement ms, Object parameter) throws SQLException;  //查询,带分页,带缓存,BoundSql   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  CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql);  //判断是否缓存了  boolean isCached(MappedStatement ms, CacheKey key);  //清理Session缓存  void clearLocalCache();  //延迟加载  void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class targetType);  Transaction getTransaction();  void close(boolean forceRollback);  boolean isClosed();  void setExecutorWrapper(Executor executor);}

在mybatis源码中,Executor的子类为BaseExecutor,BaseExecutor是执行器的基类

public abstract class BaseExecutor implements Executor {  private static final Log log = LogFactory.getLog(BaseExecutor.class);  protected Transaction transaction;  protected Executor wrapper;  //延迟加载队列(线程安全)  protected ConcurrentLinkedQueue deferredLoads;  //本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询(一级缓存)  //本地缓存  protected PerpetualCache localCache;  //本地输出参数缓存  protected PerpetualCache localOutputParameterCache;  protected Configuration configuration;  //查询堆栈  protected int queryStack = 0;  private boolean closed;}

BatchExecutor、CachingExecutor、ReuseExecutor、SimpleExecutor都是BaseExecutor的子类

  • BatchExecutor
// 批量操作执行器public class BatchExecutor extends BaseExecutor {  public static final int BATCH_UPDATE_RETURN_VALUE = Integer.MIN_VALUE + 1002;  private final List statementList = new ArrayList();  private final List batchResultList = new ArrayList();  private String currentSql;  private MappedStatement currentStatement;}
  • CachingExecutor
// 缓存执行器public class CachingExecutor implements Executor {  private Executor delegate;  private TransactionalCacheManager tcm = new TransactionalCacheManager();}
  • ReuseExecutor
// 可重用执行器public class ReuseExecutor extends BaseExecutor {  //可重用的执行器内部用了一个map,key为执行的sql,value为sql对应的Statement  private final Map statementMap = new HashMap();}
  • SimpleExecutor
// 简单执行器public class SimpleExecutor extends BaseExecutor {}
0