深入理解 MyBatis - PooledDataSource

深入理解 MyBatis - PooledDataSource

  • 原文地址:
  • 原文作者:
  • 本文永久链接:
特别说明

当前文章内容迁移中,如有问题,请提交 issues 谢谢~~

我们在进行数据库链接操作时,会通过 JDBCconnection 进行数据库操作。但是频繁的创建和销毁 connection 会影响执行效率。因此 MyBatis 中存在连接池技术

  • pooled
  • unpooled

PooledDataSource 分析

数据库基础配置以及事务的隔离级别

 
  private String driver;
  private String url;
  private String username;
  private String password;

  private Boolean autoCommit;
  private Integer defaultTransactionIsolationLevel;

初始化时,会加载并注册驱动

  static {
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) &#123;
      Driver driver = drivers.nextElement();
      registeredDrivers.put(driver.getClass().getName(), driver);
    &#125;
  &#125;

获取数据库的连接时,会调用以下方法

  1. 构造配置文件,用户名和密码,准备链接
  2. 加载驱动,准备链接
  3. 获取数据库连接
  4. 对连接进行配置
public class UnpooledDataSource implements DataSource &#123;

  private Connection doGetConnection(String username, String password) throws SQLException &#123;
    Properties props = new Properties();
    if (driverProperties != null) &#123;
      props.putAll(driverProperties);
    &#125;
    if (username != null) &#123;
      props.setProperty("user", username);
    &#125;
    if (password != null) &#123;
      props.setProperty("password", password);
    &#125;
    return doGetConnection(props);
  &#125;

  private Connection doGetConnection(Properties properties) throws SQLException &#123;
    initializeDriver();
    Connection connection = DriverManager.getConnection(url, properties);
    configureConnection(connection);
    return connection;
  &#125;

初始化驱动

  private synchronized void initializeDriver() throws SQLException &#123;
    if (!registeredDrivers.containsKey(driver)) &#123;
      Class<?> driverType;
      try &#123;
        if (driverClassLoader != null) &#123;
          driverType = Class.forName(driver, true, driverClassLoader);
        &#125; else &#123;
          driverType = Resources.classForName(driver);
        &#125;
        // DriverManager requires the driver to be loaded via the system ClassLoader.
        // http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
        Driver driverInstance = (Driver)driverType.newInstance();
        DriverManager.registerDriver(new DriverProxy(driverInstance));
        registeredDrivers.put(driver, driverInstance);
      &#125; catch (Exception e) &#123;
        throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
      &#125;
    &#125;
  &#125;

对链接进行配置,查看是否是自动提交,是否存在配置的事务隔离级别

  private void configureConnection(Connection conn) throws SQLException &#123;
    if (autoCommit != null && autoCommit != conn.getAutoCommit()) &#123;
      conn.setAutoCommit(autoCommit);
    &#125;
    if (defaultTransactionIsolationLevel != null) &#123;
      conn.setTransactionIsolation(defaultTransactionIsolationLevel);
    &#125;
  &#125;
&#125;
Prev:
redis-lua 简介
Next:
单元测试 - Mockito - powermock - 异常测试
Contents of this article
Contents of this article