Mybatis-Session生成详细分析

在上一篇的分析中我们分析了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。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值