mybatis sqlSession.getConnection()调用过程

Connection connection = sqlSession.getConnection();

public class DefaultSqlSession implements SqlSession {

	  private final Configuration configuration;
	  private final Executor executor;
	
	  @Override
	  public Connection getConnection() {
	      return executor.getTransaction().getConnection();
	  }

}

public class CachingExecutor implements Executor {

	  private final Executor delegate;
	
	  public CachingExecutor(Executor delegate) {
	    this.delegate = delegate;
	    delegate.setExecutorWrapper(this);
	  }
	
	  @Override
	  public Transaction getTransaction() {
	    return delegate.getTransaction();
	  }

}

public class ManagedTransaction implements Transaction {

	  private DataSource dataSource;
	  private TransactionIsolationLevel level;
	  private Connection connection;
	
	  @Override
	  public Connection getConnection() throws SQLException {
	    if (this.connection == null) {
	      openConnection();
	    }
	    return this.connection;
	  }
	
	  protected void openConnection() throws SQLException {
	 
	    this.connection = this.dataSource.getConnection(); // 111
	    if (this.level != null) {//设置事务隔离级别
	      this.connection.setTransactionIsolation(this.level.getLevel());//222
	    }
	  }

}

//111
public class MysqlDataSource extends JdbcPropertySetImpl implements DataSource, Referenceable, Serializable, JdbcPropertySet {
    @Override
    public java.sql.Connection getConnection() throws SQLException {
        return getConnection(this.user, this.password);
    }

    @Override
    public java.sql.Connection getConnection(String userID, String pass) throws SQLException {
        Properties props = exposeAsProperties();//获取数据库用户名和密码

        if (userID != null) {
            props.setProperty(PropertyKey.USER.getKeyName(), userID);
        }

        if (pass != null) {
            props.setProperty(PropertyKey.PASSWORD.getKeyName(), pass);
        }

        return getConnection(props);
    }

    protected java.sql.Connection getConnection(Properties props) throws SQLException {
        String jdbcUrlToUse = this.explicitUrl ? this.url : getUrl();//获取数据库url
        return mysqlDriver.connect(jdbcUrlToUse, props);
    }

}

public class NonRegisteringDriver implements java.sql.Driver {

    @Override
    public java.sql.Connection connect(String url, Properties info) throws SQLException {

            if (!ConnectionUrl.acceptsUrl(url)) {
                return null;
            }

            ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
            switch (conStr.getType()) {
                case SINGLE_CONNECTION:
                    return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost()); // 666

                case FAILOVER_CONNECTION:
                case FAILOVER_DNS_SRV_CONNECTION:
                    return FailoverConnectionProxy.createProxyInstance(conStr);  //777

                case LOADBALANCE_CONNECTION:
                case LOADBALANCE_DNS_SRV_CONNECTION:
                    return LoadBalancedConnectionProxy.createProxyInstance(conStr);

                case REPLICATION_CONNECTION:
                case REPLICATION_DNS_SRV_CONNECTION:
                    return ReplicationConnectionProxy.createProxyInstance(conStr);

                default:
                    return null;
            }

    }

}

//666: 根据主机信息获取连接 : ConnectionImpl impl JdbcConnection ext java.sql.Connection 
public class ConnectionImpl implements JdbcConnection, SessionEventListener, Serializable {
    public static JdbcConnection getInstance(HostInfo hostInfo) throws SQLException {
        return new ConnectionImpl(hostInfo);//构造方法中初始化主机信息
    }
}

//777
public class FailoverConnectionProxy extends MultiHostConnectionProxy {

 public static JdbcConnection createProxyInstance(ConnectionUrl connectionUrl) throws SQLException {
        FailoverConnectionProxy connProxy = new FailoverConnectionProxy(connectionUrl);
        //创建代理
        return (JdbcConnection) java.lang.reflect.Proxy.newProxyInstance(JdbcConnection.class.getClassLoader(), new Class<?>[] { JdbcConnection.class },
                connProxy);
    }

}

package com.mysql.cj.jdbc;//Mysql实现 
public class ConnectionImpl implements JdbcConnection, SessionEventListener, Serializable {//222

  //默认隔离级别 READ_COMMITTED
  private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED;

  //更新隔离级别
  private NativeSession session = null;

 	@Override
    public void setTransactionIsolation(int level) throws SQLException {
        synchronized (getConnectionMutex()) {
            checkClosed();

            String sql = null;

            boolean shouldSendSet = false;

            if (this.propertySet.getBooleanProperty(PropertyKey.alwaysSendSetIsolation).getValue()) {
                shouldSendSet = true;
            } else {
                if (level != this.isolationLevel) {//隔离级别与默认不相等
                    shouldSendSet = true;
                }
            }

            if (this.useLocalSessionState.getValue()) {
                shouldSendSet = this.isolationLevel != level;
            }

            if (shouldSendSet) {
                switch (level) {
                    case java.sql.Connection.TRANSACTION_NONE: //0
                        throw SQLError.createSQLException(Messages.getString("Connection.24"), getExceptionInterceptor());

                    case java.sql.Connection.TRANSACTION_READ_COMMITTED: //1
                        sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";

                        break;

                    case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED://2
                        sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";

                        break;

                    case java.sql.Connection.TRANSACTION_REPEATABLE_READ: //4
                        sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";

                        break;

                    case java.sql.Connection.TRANSACTION_SERIALIZABLE: //8
                        sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";

                        break;

                    default:
                        throw SQLError.createSQLException(Messages.getString("Connection.25", new Object[] { level }),
                                MysqlErrorNumbers.SQL_STATE_DRIVER_NOT_CAPABLE, getExceptionInterceptor());
                }

 			    //调用 com.mysql.cj.NativeSession 执行更新
                this.session.execSQL(null, sql, -1, null, false, this.nullStatementResultSetFactory, null, false);//执行sql,更新隔离级别

                this.isolationLevel = level;//成员变量隔离级别重新赋值
            }
        }
    }

}


public interface Connection  extends Wrapper, AutoCloseable {

	int TRANSACTION_NONE             = 0;
	int TRANSACTION_READ_UNCOMMITTED = 1;
	int TRANSACTION_READ_COMMITTED   = 2;
	int TRANSACTION_REPEATABLE_READ  = 4;
	int TRANSACTION_SERIALIZABLE     = 8;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis 中,获取连接超时时间需要通过配置文件进行设置。具体方法如下: 1. 在 MyBatis 的配置文件中,添加如下配置: ```xml <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> <property name="poolMaximumActiveConnections" value="10"/> <property name="poolMaximumIdleConnections" value="5"/> <property name="poolMaximumCheckoutTime" value="20000"/> <property name="poolTimeToWait" value="20000"/> </dataSource> </environment> ``` 在 `<dataSource>` 标签中,可以设置连接池的相关属性,其中: - `poolMaximumActiveConnections`:连接池中允许的最大活动连接数,默认值是 10。 - `poolMaximumIdleConnections`:连接池中允许的最大空闲连接数,默认值是 5。 - `poolMaximumCheckoutTime`:连接池中连接的最大存活时间,默认值是 20000(即 20 秒)。 - `poolTimeToWait`:在连接池中获取连接时等待的最长时间,默认值是 20000(即 20 秒)。 2. 在 Java 代码中,通过 `SqlSessionFactoryBuilder` 创建 `SqlSessionFactory` 对象,并传入配置文件的路径,如下: ```java String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); ``` 3. 在 Java 代码中,通过 `SqlSessionFactory` 创建 `SqlSession` 对象,并调用 `getConnection()` 方法获取连接,如下: ```java SqlSession sqlSession = sqlSessionFactory.openSession(); Connection connection = sqlSession.getConnection(); ``` 在获取连接的过程中,如果连接池中没有可用的连接,会等待 `poolTimeToWait` 毫秒,如果等待超时,则会抛出 `org.apache.ibatis.exceptions.PersistenceException` 异常。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值