包详解
...大约 6 分钟
包详解
transaction包

背景知识
- 工厂模式
 
讲解
这里并没有特别需要说的东西,只是基础的事务管理。但是这里很好的实现了transaction和datasource包的隔离,transaction通过datasource抽象出来的接口实现了业务隔离,事务管理器可以通过配置文件选择对应的数据源进行管理。
jdbc包
背景知识
- 模版模式
 - 易用性
 
讲解
模版模式
某些类通用的一些处理方法一致,但是处理对象可能存在不同,此时可以使用模版方法,抽取父类编写通用处理方法,子类只需实现获取对象的方法即可。
public class SQL extends AbstractSQL<SQL> {
    @Override
    public SQL getSelf() {
        return this;
    }
}
public abstract class AbstractSQL<T> {
    private static final String AND = ") \nAND (";
    private static final String OR = ") \nOR (";
    private final SQLStatement sql = new SQLStatement();
    public abstract T getSelf();
    public T UPDATE(String table) {
        sql().statementType = SQLStatement.StatementType.UPDATE;
        sql().tables.add(table);
        return getSelf();
    }
    public T SET(String sets) {
        sql().sets.add(sets);
        return getSelf();
    }
		......
}
以上代码可知:
- 若用户需要自定
SQL如ExplainSQL,从而进行性能调优,此时只需要继承AbstractSQL即可,而无需编写原方法。 
易用性
为了用户使用方便和构建 SQL的直观性,AbstractSQL命名采用了全大写的模式,以此让用户更加易用。

SqlRunner类
    public int insert(String sql, Object... args) throws SQLException {
        PreparedStatement ps;
        if (useGeneratedKeySupport) {
            ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        } else {
            ps = connection.prepareStatement(sql);
        }
        try {
            setParameters(ps, args);
            ps.executeUpdate();
            if (useGeneratedKeySupport) {
                List<Map<String, Object>> keys = getResults(ps.getGeneratedKeys());
                if (keys.size() == 1) {
                    Map<String, Object> key = keys.get(0);
                    Iterator<Object> i = key.values().iterator();
                    if (i.hasNext()) {
                        Object genkey = i.next();
                        if (genkey != null) {
                            try {
                                return Integer.parseInt(genkey.toString());
                            } catch (NumberFormatException e) {
                                //ignore, no numeric key support
                            }
                        }
                    }
                }
            }
            return NO_GENERATED_KEY;
        } finally {
            try {
                ps.close();
            } catch (SQLException e) {
                //ignore
            }
        }
    }
    public int update(String sql, Object... args) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(sql);
        try {
            setParameters(ps, args);
            return ps.executeUpdate();
        } finally {
            try {
                ps.close();
            } catch (SQLException e) {
                //ignore
            }
        }
    }
此类在Mybatis中没有任何的使用,此类应该只是为了提供给用户,让用户可以自定义执行相关 SQL,分析其方法本质为原始JDBC相关操作流程。
ScriptRunner类
   private void executeFullScript(Reader reader) {
        StringBuilder script = new StringBuilder();
        try {
            BufferedReader lineReader = new BufferedReader(reader);
            String line;
            while ((line = lineReader.readLine()) != null) {
                script.append(line);
                script.append(LINE_SEPARATOR);
            }
            String command = script.toString();
            println(command);
            executeStatement(command);
            commitConnection();
        } catch (Exception e) {
            String message = "Error executing: " + script + ".  Cause: " + e;
            printlnError(message);
            throw new RuntimeSqlException(message, e);
        }
    }
    private void executeLineByLine(Reader reader) {
        StringBuilder command = new StringBuilder();
        try {
            BufferedReader lineReader = new BufferedReader(reader);
            String line;
            while ((line = lineReader.readLine()) != null) {
                handleLine(command, line);
            }
            commitConnection();
            checkForMissingLineTerminator(command);
        } catch (Exception e) {
            String message = "Error executing: " + command + ".  Cause: " + e;
            printlnError(message);
            throw new RuntimeSqlException(message, e);
        }
    }
    private void handleLine(StringBuilder command, String line) throws SQLException {
        String trimmedLine = line.trim();
        if (lineIsComment(trimmedLine)) {
            Matcher matcher = DELIMITER_PATTERN.matcher(trimmedLine);
            if (matcher.find()) {
                delimiter = matcher.group(5);
            }
            println(trimmedLine);
        } else if (commandReadyToExecute(trimmedLine)) {
            command.append(line.substring(0, line.lastIndexOf(delimiter)));
            command.append(LINE_SEPARATOR);
            println(command);
            executeStatement(command.toString());
            command.setLength(0);
        } else if (trimmedLine.length() > 0) {
            command.append(line);
            command.append(LINE_SEPARATOR);
        }
    }
此类的核心方法如上,可看出其本质和SqlRunner类一致。
datasource包

根据包结构可看出,Mybatis抽象出DataSourceFactory进行生成对应的DataSource。可以知道DataSourceFactory的设计是采用了工厂模式。
背景知识
- 数据库连接池
 - JNDI
 - 设计模式:工厂模式、模版模式、代理模式
 
讲解
数据库连接池
数据库在建立连接的时候需要走 TCP 的三次握手,如果在三次握手之后却只进行了一次查询这就会浪费较多的资源,所以想到了池化思想,对数据库连接进行池化,减少数据库连接的创建和销毁的资源浪费。
 数据库连接池的本质就是建立一个集合进行存储创建的连接,当有需要查询的时候从缓存的连接中返回一个,等使用完毕不再进行销毁而是再次放回到缓存中,此时就需要对连接部分方法的重写,但是 Mybatis是通过代理进行处理。代码如下:
       @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        // 当调用的方法是close 的时候不去进行真正的关闭,而是将连接放回连接池中
        if (CLOSE.hashCode() == methodName.hashCode() && CLOSE.equals(methodName)) {
            dataSource.pushConnection(this);
            return null;
        } else {
            try {
                if (!Object.class.equals(method.getDeclaringClass())) {
                    // issue #579 toString() should never fail
                    // throw an SQLException instead of a Runtime
                    checkConnection();
                }
                return method.invoke(realConnection, args);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        }
    }
JNDI
TODO 待了解
设计模式
- 即使工厂模式,也是模版模式
 - 代理模式
 
    public PooledConnection(Connection connection, PooledDataSource dataSource) {
    this.hashCode = connection.hashCode();
    this.realConnection = connection;
    this.dataSource = dataSource;
    this.createdTimestamp = System.currentTimeMillis();
    this.lastUsedTimestamp = System.currentTimeMillis();
    this.valid = true;
    // 创建 connection 的代理对象,进行代理所有的请求
    this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), IFACES, this);
}
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    // 拦截调用close方法,不去进行真正的关闭,而是将连接放回连接池中
    if (CLOSE.hashCode() == methodName.hashCode() && CLOSE.equals(methodName)) {
        dataSource.pushConnection(this);
        return null;
    } else {
        try {
            if (!Object.class.equals(method.getDeclaringClass())) {
                // issue #579 toString() should never fail
                // throw an SQLException instead of a Runtime
                checkConnection();
            }
            return method.invoke(realConnection, args);
        } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
    }
}
exception包
下图是Mybatis中异常的关系图:

背景知识
- 工厂模式
 - 异常的封装
 
讲解
工厂模式
public class ExceptionFactory {
    private ExceptionFactory() {
        // Prevent Instantiation
    }
    public static RuntimeException wrapException(String message, Exception e) {
        return new PersistenceException(ErrorContext.instance().message(message).cause(e).toString(), e);
    }
}
- 私有构造函数:导致该工厂无法创建出对应的对象
 - 静态
wrapException方法,用于通过异常信息和异常类型进行封装异常为Mybatis中的异常类型。全局通过ExceptionFactory.wrapException()进行生产出对应的异常对象 
异常类型
- IbatisException:
Mybatis中最高的异常,但是直接继承该类的子类只有PersistenceException,而且该类也添加了@Deprecated说明以后可能去除。 - PersistenceException: 译为持久化异常。
Mybatis对应是持久化框架,后期可能该异常类型为Mybatis所有异常的父类。 - TooManyResultsException:译为多条返回结果异常。用处为
selectOne却返回多条记录时所抛出的异常。 - TypeException: 译为类型异常。当 
Mybatis中需要类型转化时,若转换失败则会抛出该异常。 - CacheException: 译为缓存异常。当
Mybatis读取缓存中数据出现问题时则会抛出该异常。 - ParsingException: 译为解析异常。当前代码未看到使用。
 - ScriptingException: 译为脚本异常。
 - ResultMapException: 译为结果映射异常。在结果转换为对应类型的对象时,若转换失败则会抛出异常。
 - DataSourceException: 译为数据源异常。在初始化数据源时若出现错误则会抛出该异常。
 - TransactionException: 译为事务异常。在给
connection开启事务时若失败则会抛出该异常。 - BuilderException: 译为建造异常。在建造对象失败时会抛出该异常。
 - SqlSessionException: 译为
SqlSession的异常。基本只会在SqlSessionManager中使用,主要是SqlSession使用过程中的异常。 - ReflectionException: 译为反射异常。基本只会在反射使用时会抛出该异常。
 - ExecutorException: 译为执行器异常。会在线程操作数据库的时候抛出该异常。
 - BatchExecutorException:译为批量执行器异常。会在线程批量操作数据库的时候抛出该异常。
 - BindingException: 译为绑定异常。主要是 
mapper映射的时候会抛出该异常。 - LogException: 译为日志异常。目前只在
LogFactory构建日志相关的时候才会抛出该异常。 - PluginException: 译为插件异常。目前只在
Plugin中使用,在获取插件信息时候会抛出该异常。 
Mybatis类型主要是根据业务相关包放在一起,所以命名绝大多数都能够直观的看到原因所在。
annotations和 lang包
背景知识
讲解
 Powered by  Waline  v3.1.3
