MyBatis - SqlSession(上)

简介: MyBatis - SqlSession(上)

前面的章节主要讲mybatis如何解析配置文件,这些都是一次性的过程。从本章开始讲解动态的过程,它们跟应用程序对mybatis的调用密切相关。本章先从sqlsession开始。



一、SqlSession

1、创建

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


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

我们可以看到实际创建SqlSession的地方是openSessionFromDataSource,如下:

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Connection connection = null;
    try {
        final Environment environment = configuration.getEnvironment();
        final DataSource dataSource = getDataSourceFromEnvironment(environment);
       TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
       connection = dataSource.getConnection();
        if (level != null) {
           connection.setTransactionIsolation(level.getLevel());
        }
        connection = wrapConnection(connection);
        Transaction tx = transactionFactory.newTransaction(connection,autoCommit);
        Executor executor = configuration.newExecutor(tx, execType);
        return newDefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exceptione) {
        closeConnection(connection);
        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

1、创建

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


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

可以看出,如果不开启cache的话,创建的Executor只是3种基础类型之一,BatchExecutor专门用于执行批量sql操作,ReuseExecutor会重用statement执行sql操作,SimpleExecutor只是简单执行sql没有什么特别的。开启cache的话(默认是开启的并且没有任何理由去关闭它),就会创建CachingExecutor,它以前面创建的Executor作为唯一参数。CachingExecutor在查询数据库前先查找缓存,若没找到的话调用delegate(就是构造时传入的Executor对象)从数据库查询,并将查询结果存入缓存中。

Executor对象是可以被插件拦截的,如果定义了针对Executor类型的插件,最终生成的Executor对象是被各个插件插入后的代理对象(关于插件会有后续章节专门介绍,敬请期待)。



三、Mapper

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

session = sqlSessionFactory.openSession();
UserDao userDao= session.getMapper(UserDao.class);
UserDto user =new UserDto();
user.setUsername("iMbatis");
user.setPassword("iMbatis");
userDao.insertUser(user);

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

1、创建

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

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    if (!knownMappers.contains(type))
        throw new BindingException("Type " + type + " isnot known to the MapperRegistry.");
    try {
        return MapperProxy.newMapperProxy(type, sqlSession);
    } catch (Exceptione) {
        throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
}

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

public static <T> T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
    ClassLoader classLoader = mapperInterface.getClassLoader();
    Class<?>[] interfaces = new Class[]{mapperInterface};
    MapperProxy proxy = new MapperProxy(sqlSession);
    return (T) Proxy.newProxyInstance(classLoader,interfaces, proxy);
}

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

2、MapperProxy 的 invoke

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

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
    if (method.getDeclaringClass()== Object.class) {
        return method.invoke(this, args);
    }
    final Class<?> declaringInterface = findDeclaringInterface(proxy, method);
    final MapperMethod mapperMethod = new MapperMethod(declaringInterface, method, sqlSession);
    final Object result = mapperMethod.execute(args);
    if (result ==null && method.getReturnType().isPrimitive()&& !method.getReturnType().equals(Void.TYPE)) {
        throw new BindingException("Mapper method '" + method.getName() + "'(" + method.getDeclaringClass()
                + ") attempted toreturn null from a method with a primitive return type ("
               + method.getReturnType() + ").");
    }
    return result;
}

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

public Object execute(Object[] args) {
    Object result = null;
    if(SqlCommandType.INSERT == type) {
        Object param = getParam(args);
        result = sqlSession.insert(commandName, param);
    } else if(SqlCommandType.UPDATE == type) {
        Object param = getParam(args);
        result = sqlSession.update(commandName, param);
    } else if(SqlCommandType.DELETE == type) {
        Object param = getParam(args);
        result = sqlSession.delete(commandName, param);
    } else if(SqlCommandType.SELECT == type) {
        if (returnsVoid && resultHandlerIndex != null) {
           executeWithResultHandler(args);
        } else if (returnsList) {
           result = executeForList(args);
        } else if (returnsMap) {
           result = executeForMap(args);
        } else {
           Object param = getParam(args);
           result = sqlSession.selectOne(commandName, param);
        }
    } else {
        throw new BindingException("Unknown execution method for: " + commandName);
    }
    return result;
}

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

目录
相关文章
|
SQL 缓存 Java
MyBatis核心 - SqlSession如何通过Mapper接口生成Mapper对象
从 SqlSessionFactoryBuilder - SqlSessionFactory - SqlSession - Mapeper实例对象 的过程
364 0
|
SQL Java 数据库连接
MyBatis之魂:探索核心接口SqlSession的神秘力量
MyBatis之魂:探索核心接口SqlSession的神秘力量
174 3
MyBatis之魂:探索核心接口SqlSession的神秘力量
|
SQL Java 数据库连接
Mybatis之SqlSession简析
Mybatis之SqlSession简析
343 0
|
Java 数据库连接 mybatis
使用Mybatis获取sqlSession对象老爆红的问题解决
使用Mybatis获取sqlSession对象老爆红的问题解决
|
XML Java 数据库连接
Mybatis之简介、使用操作(安装、XML、SqlSession、映射的SQL语句、命名空间、作用域和生命周期)
【1月更文挑战第2天】 MyBatis 是一款优秀的持久层框架 MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程 MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
276 2
Mybatis之简介、使用操作(安装、XML、SqlSession、映射的SQL语句、命名空间、作用域和生命周期)
|
SQL Java 数据库连接
一篇看懂Mybatis的SqlSession运行原理
SqlSession是Mybatis最重要的构建之一,可以简单的认为Mybatis一系列的配置目的是生成类似 JDBC生成的Connection对象的SqlSession对象,这样才能与数据库开启“沟通”,通过SqlSession可以实现增删改查(当然现在更加推荐是使用Mapper接口形式),那么它是如何执行实现的,这就是本篇博文所介绍的东西,其中会涉及到简单的源码讲解。
357 1
|
缓存 Java 数据库连接
一文彻底搞懂Mybatis系列(十)之SqlSession、SqlSessionFactory和SqlSessionFactoryBuilder详解
一文彻底搞懂Mybatis系列(十)之SqlSession、SqlSessionFactory和SqlSessionFactoryBuilder详解
1394 1
|
设计模式 缓存 Java
MyBatis原理分析之获取SqlSession
MyBatis原理分析之获取SqlSession
431 0
Mybatis插入大量数据效率对比:foreach、SqlSession批量、sql
使用mybatis插入数据执行效率对比,对比三种方式(测试数据库为MySQL), 使用 SqlSessionFactory,每一批数据执行一次提交 使用mybatis-plus框架的insert方法,for循环,每次执行一次插入 使用ibatis,纯sql插入
|
Java 数据库连接 mybatis
Mybatis之Error building SqlSession.
Mybatis之Error building SqlSession.
760 0