MapperMethod:映射器方法
映射器方法是最底层的被调用者,同时也是binding模块中最复杂的内容。它是MyBatis中对SqlSession会话操作的封装,那么这意味着什么呢?意味着这个类可以看做是整个MyBatis中数据库操作的枢纽,所有的数据库操作都需要经过它来得以实现。
我们单独使用MyBatis时,有时会直接操作SqlSession会话进行数据库操作,但是在SSM整合之后,这个数据库操作却是自动完成的,那么Sqlsession就需要被自动执行,那么组织执行它的就是这里的MapperMethod。
SqlSession会作为参数在从MapperRegisty中getMapper()中一直传递到MapperMethod中的execute()方法中,然后在这个方法中进行执行。
字段
““java
/**
* sql语句
*/
private final SqlCommand command;
/**
* 方法签名
*/
private final MethodSignature method;
““
这两个字段类型都是以MapperMethod中的静态内部类的方式定义的,分别表示sql命令与接口中的方法。
这两个字段都是final修饰,表示不可变,即一旦赋值,就永远是该值。
构造器
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
使用构造器对上面的两个字段进行赋值,这个赋值是永久的。
核心方法:execute()
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//可以看到执行时就是4种情况,insert|update|delete|select,分别调用SqlSession的4大类方法
switch (command.getType()) {
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;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
//如果有结果处理器
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) { //如果结果有多条记录
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) { //如果结果是map
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
//否则就是一条记录
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;