mybatis_helloworld(2)_源码(四)

2014-11-24 08:22:29 · 作者: · 浏览: 7
}
}
4. insert数据的实现
[java]
public int insert(String statement, Object parameter)
{
return update(statement, parameter);
}
public int update(String statement, Object parameter)
{
try
{
int i;
try
{
dirty = true;
//根据Mapper.xml配置文件中的id找到Sql语句
org.apache.ibatis.mapping.MappedStatement ms = configuration.getMappedStatement(statement);
//这个执行器是不是见过?构建DefaultSqlSession时传过来的
// org.apache.ibatis.executor.Executor executor = configuration.newExecutor(tx, execType);
i = executor.update(ms, wrapCollection(parameter));
}
catch(Exception e)
{
throw ExceptionFactory.wrapException((new StringBuilder()).append("Error updating database. Cause: ").append(e).toString(), e);
}
return i;
}
finally
{
ErrorContext.instance().reset();
}
}
a) 找一下executor,看看其update方法
i. 调用哪个executor?
[java]
public Executor newExecutor(Transaction transaction, ExecutorType executorType)
{
executorType = executorType != null executorType : defaultExecutorType; //我们使用的是默认的Type(SIMPLE)
executorType = executorType != null executorType : ExecutorType.SIMPLE;
Executor executor;
if(ExecutorType.BATCH == executorType)
executor = new BatchExecutor(this, transaction);
else
if(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;
}
ii. SimpleExecutor的update方法实现
[java]
//父类BaseExecutor的update方法,调用了doUpdate方法
public int update(MappedStatement ms, Object parameter)
throws SQLException
{
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if(closed)
{
throw new ExecutorException("Executor was closed.");
} else
{
clearLocalCache();
return doUpdate(ms, parameter);
}
}
//子类SimpleExecutor重写了doUpdate方法
public int doUpdate(MappedStatement ms, Object parameter)
throws SQLException
{
//java.sql.Statement
Statement stmt = null;
int i;
try
{
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null);
//大概就是拼Sql,生成对应的Statement,执行Sql,封装数据了(这块比较复杂,下次再看了)
stmt = prepareStatement(handler);
i = handler.update(stmt);
}
finally
{
closeStatement(stmt);
}
return i;
}
看了一回源码,也感觉高端大气上档次了,下次画个图