由于MapperMethod中Insert,update,delete这三个的执行方式是一样的,我们统一看一下
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
这里都是两步,①执行sqlsession的对应方法②对执行结果进行处理
1.执行sqlsession的对应方法:最终都是走的update方法
public int insert(String statement) {
return insert(statement, null);
}
@Override
public int insert(String statement, Object parameter) {
return update(statement, parameter);
}
@Override
public int update(String statement) {
return update(statement, null);
}
@Override
public int delete(String statement) {
return update(statement, null);
}
@Override
public int delete(String statement, Object parameter) {
return update(statement, parameter);
}
@Override
public int update(String statement, Object parameter) {
try {
dirty = true;
//1.根据ID获取MappedStatement
MappedStatement ms = configuration.getMappedStatement(statement);
//2.对集合参数进行处理
//3.执行executor的update方法
return executor.update(ms, wrapCollection(parameter));
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
1.1根据ID获取MappedStatement 对象:缓存中获取
public MappedStatement getMappedStatement(String id) {
return this.getMappedStatement(id, true);
}
public MappedStatement getMappedStatement(String id, boolean validateIncompleteStatements) {
if (validateIncompleteStatements) {
buildAllStatements();
}
return mappedStatements.get(id);
}
1.2对集合参数进行处理
private Object wrapCollection(final Object object) {
//如果是集合类型的参数
if (object instanceof Collection) {
//参数以,map形式返回
StrictMap<Object> map = new StrictMap<Object>();
//设置参数名称为collection
map.put("collection", object);
//如果是list类型
if (object instanceof List) {
//设置参数名称为list
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
//如果是数组类型,以map形式返回
//设置参数名称为array
StrictMap<Object> map = new StrictMap<Object>();
map.put("array", object);
return map;
}
//不是集合和数组类型 原样返回
return object;
}
1.3执行executor(B