Mybatis-Session生成详细分析

来源:互联网 发布:癌症晚期知乎 编辑:程序博客网 时间:2024/04/30 13:36

在上一篇的分析中我们分析了Mybatis-SessionFactory,这一篇我们详细分析session.

分析入口代码:

SqlSession sqlSession=MyBatisSqlSessionFactory.openSession();

1。

  public SqlSession openSession() {        return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);    }

this.configuration.getDefaultExecutorType(),获得我们默认的ExecutorType类型,这里类型有三种Batch(批量查询和重用语句),REUSE(重用语句),Simple(预编译)。可以在我们的配置文件中配置defaultExecutorType。

在这里第二个参数是TransactionIsolationLevel,我们可以指定当前session的事务级别,TransactionIsolationLevel是枚举类如下:

public enum TransactionIsolationLevel {    NONE(0),//没有事务    READ_COMMITTED(2),//已提交读,不能阻止脏读。    READ_UNCOMMITTED(1),//未提交读,等级最低。    REPEATABLE_READ(4),//不可重复读,阻止脏读不能避免幻读    SERIALIZABLE(8);//阻止了所有读    private final int level;    private TransactionIsolationLevel(int level) {        this.level = level;    }    public int getLevel() {        return this.level;    }}

第三个参数是设置是否自动提交。

2。继续跟踪代码

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {        Transaction tx = null;        DefaultSqlSession var8;        try {            Environment e = this.configuration.getEnvironment();            TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(e);            tx = transactionFactory.newTransaction(e.getDataSource(), level, autoCommit);            Executor executor = this.configuration.newExecutor(tx, execType);            var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);        } catch (Exception var12) {            this.closeTransaction(tx);            throw ExceptionFactory.wrapException("Error opening session.  Cause: " + var12, var12);        } finally {            ErrorContext.instance().reset();        }        return var8;    }

在这段代码中,
1.得到环境。
2.通过当前环境,得到事务工厂,在我们的代码中得到的是jdbc事务工厂。

<transactionManager type="jdbc"></transactionManager>

3.通过工厂和我们设定的事务等级,获得事务Transaction,我们进入该接口中:

public interface Transaction {    Connection getConnection() throws SQLException;//得到当前连接    void commit() throws SQLException;//提交    void rollback() throws SQLException;//回滚    void close() throws SQLException;//关闭}

4.事务完成之后,接下来我们生成Executor执行器,这是我们核心,我们在sqlsession中执行的代码都是在Executor中执行的,以后具体分析。
5。生成默认的
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
然后发挥sqlsession。

0 0