DefaultSqlSession第三讲-事务提交,回滚,关闭SqlSession,清除缓存

阅读更多
上面两篇讲过query和update及flushStatements,这篇我们讲一下commit,rollback,clearCache,close
public class DefaultSqlSession
    implements SqlSession
{
    private Configuration configuration;
    private Executor executor;
    private boolean dirty;
    public DefaultSqlSession(Configuration configuration, Executor executor)
    {
        this.configuration = configuration;
        this.executor = executor;
        dirty = false;
    }
    //查询
    public Object selectOne(String statement)
    {
        return selectOne(statement, null);
    }
    public Object selectOne(String statement, Object parameter)
    {
        List list = selectList(statement, parameter);
        if(list.size() == 1)
            return list.get(0);
        if(list.size() > 1)
            throw new TooManyResultsException((new StringBuilder()).append("Expected one result (or null) to be returned by selectOne(), but found: ").append(list.size()).toString());
        else
            return null;
    }
    public List selectList(String statement)
    {
        return selectList(statement, null);
    }

    public List selectList(String statement, Object parameter)
    {
        return selectList(statement, parameter, RowBounds.DEFAULT);
    }
    public List selectList(String statement, Object parameter, RowBounds rowBounds)
    {
        List list;
        try
        {
            org.apache.ibatis.mapping.MappedStatement ms = configuration.getMappedStatement(statement);
	    //调用executor的查询方法
            List result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
            list = result;
        }
    }
    //插入
     public int insert(String statement)
    {
        return insert(statement, null);
    }

    public int insert(String statement, Object parameter)
    {
       //委托给update方法
        return update(statement, parameter);
    }

    public int update(String statement)
    {
        return update(statement, null);
    }

    public int update(String statement, Object parameter)
    {
        int i;
        try
        {
            dirty = true;
            org.apache.ibatis.mapping.MappedStatement ms = configuration.getMappedStatement(statement);
            //委托给executor的update
	    i = executor.update(ms, wrapCollection(parameter));
        }
    }
    //删除
     public int delete(String statement)
    { 
        //委托给update
        return update(statement, null);
    }

    public int delete(String statement, Object parameter)
    {
        return update(statement, parameter);
    }
    //提交
     public void commit()
    {
        commit(false);
    }

    public void commit(boolean force)
    {
        try
        {
	    //委托executor的commit
            executor.commit(isCommitOrRollbackRequired(force));
            dirty = false;
        }
    }
    //回滚
     public void rollback()
    {
        rollback(false);
    }

    public void rollback(boolean force)
    {
        try
        {
	    //委托executor的rollback
            executor.rollback(isCommitOrRollbackRequired(force));
            dirty = false;
        }
    }
    //清除缓存
    public void clearCache()
    {
	////委托executor的clearLocalCache
        executor.clearLocalCache();
    }
    //刷新Statements
    public List flushStatements()
    {
        List list;
        try
        {
	    //委托executor的flushStatements
            list = executor.flushStatements();
        }
    }
    //关闭SqlSession
    public void close()
    {
        //委托executor的close
        executor.close(isCommitOrRollbackRequired(false));
        dirty = false;
    }
}

DefaultSqlSession的commit,rollback,clearCache,close方法,实际是调用
Executor的方法,所有这些方法在BaseExecutor中
public abstract class BaseExecutor
    implements Executor
{
    private static final Log log = LogFactory.getLog(org/apache/ibatis/executor/BaseExecutor);
    protected Transaction transaction;
    protected ConcurrentLinkedQueue deferredLoads;
    protected PerpetualCache localCache;
    protected PerpetualCache localOutputParameterCache;
    protected Configuration configuration;
    protected int queryStack;
    private boolean closed;
    //提交事务
     public void commit(boolean required)
        throws SQLException
    {
        if(closed)
            throw new ExecutorException("Cannot commit, transaction is already closed");
        clearLocalCache();
        flushStatements();
        if(required)
            transaction.commit();
    }
    //回滚事务
    public void rollback(boolean required)
        throws SQLException
    {
        if(closed)
            break MISSING_BLOCK_LABEL_49;
        clearLocalCache();
        flushStatements(true);
        if(required)
            transaction.rollback();
        break MISSING_BLOCK_LABEL_49;
        Exception exception;
        exception;
        if(required)
            transaction.rollback();
        throw exception;
    }
    //清除本地缓存
    public void clearLocalCache()
    {
        if(!closed)
        {
            localCache.clear();
            localOutputParameterCache.clear();
        }
    }
    //关闭statement
    protected void closeStatement(Statement statement)
    {
        if(statement != null)
            try
            {
                statement.close();
            }
            catch(SQLException e) { }
    }
}

从上面可以看出事务的提交与回滚实际上所以依赖于transaction,再来看JdbcTransaction
//JdbcTransaction
public class JdbcTransaction
    implements Transaction
{
    protected Connection connection;//数据库连接
    protected DataSource dataSource;//数据源
    protected TransactionIsolationLevel level;//事务级别
    protected boolean autoCommmit;
    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit)
    {
        dataSource = ds;
        level = desiredLevel;
        autoCommmit = desiredAutoCommit;
    }
   //获取Connection
  public Connection getConnection()
        throws SQLException
    {
        if(connection == null)
            openConnection();
        return connection;
    }
    //打开Connection
    protected void openConnection()
        throws SQLException
    {
        if(log.isDebugEnabled())
            log.debug("Openning JDBC Connection");
        connection = dataSource.getConnection();
        if(level != null)
	     //设置连接事务级别
            connection.setTransactionIsolation(level.getLevel());
        setDesiredAutoCommit(autoCommmit);
    }
    //提交事务
    public void commit()
        throws SQLException
    {
        if(connection != null && !connection.getAutoCommit())
        {
            if(log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Committing JDBC Connection [").append(connection).append("]").toString());
            connection.commit();
        }
    }
    //回滚事务
    public void rollback()
        throws SQLException
    {
        if(connection != null && !connection.getAutoCommit())
        {
            if(log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Rolling back JDBC Connection [").append(connection).append("]").toString());
            connection.rollback();
        }
    }
    //关闭事务
    public void close()
        throws SQLException
    {
        if(connection != null)
        {
            resetAutoCommit();
            if(log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Closing JDBC Connection [").append(connection).append("]").toString());
            connection.close();
        }
    }    
}

从上面可看出JdbcTransaction,依赖于具体的数据库。
总结:
事务的提交与回滚实际上所以依赖于transaction,transaction依赖于具体的数据库;清除缓存就是清空执行器的本地缓存;关闭SqlSession实际上是,通过执行器关闭statement。

你可能感兴趣的:(Mybatis)