mybatis-接口层

接口层

SqlSession是MyBatis核心接口之一,也是MyBatis接口层的主要组成部分,对外提供MyBatis常用API。
MyBatis提供了两个SqlSession接口的实现,这里使用了工厂方法模式,其中开发人员最常用的是DefaultSqlSession实现。
image
SqlSessionFactory负责创建SqlSession对象,其中只包含了多个openSession()方法的重载,可以通过其参数指定事务的隔离级别、底层使用Executor的类型以及是否自动提交事务等方面的配置。

在SqlSession中定义了常用的数据库操作以及事务的相关操作,为了方便用户使用,每种类型的操作都提供了多种重载。SqlSession接口的定义如下:
image

在DefaultSqlSession中使用到了策略模式,DefaultSqlSession扮演了Context的角色,而将所有数据库相关的操作全部封装到Executor接口实现中,并通过executor字段选择不同的Executor实现。

 通过构造DefaultSqlSession实例传入Executor实现用不同的Executor策略执行
 public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
    this.configuration = configuration;
    this.executor = executor;
    this.dirty = false;
    this.autoCommit = autoCommit;
  }

  public DefaultSqlSession(Configuration configuration, Executor executor) {
    this(configuration, executor, false);
  }
 
 private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
  
  public int update(String statement, Object parameter) {
    try {
      dirty = true;
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.update(ms, wrapCollection(parameter));
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error updating database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
  ...
  

posted @ 2022-04-13 22:18  liuhuayiye  阅读(83)  评论(0编辑  收藏  举报