Mybatis源码分析——参数处理

本文深入剖析了Mybatis参数处理的细节,从MapperMethod的构造到ParamNameResolver的解析过程,详细解释了如何处理@Param注解、参数名称以及如何转换参数到SqlCommand参数。在MapperMethod的execute方法中,参数被转化为Map类型,以便于执行SQL查询。同时,介绍了如何通过selectOne、selectList和update方法处理不同的参数情况,包括null、单一对象和集合对象的处理方式。
摘要由CSDN通过智能技术生成

1.构造方法

MapperMethod进行实例化,构造方法中调用静态内部类MethodSignature构造方法

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
1
2
3
4
MethodSignature构造方法中调用ParamNameResolver构造方法。

public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
if (resolvedReturnType instanceof Class<?>) {
this.returnType = (Class<?>) resolvedReturnType;
} else if (resolvedReturnType instanceof ParameterizedType) {
this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
} else {
this.returnType = method.getReturnType();
}
//… 省略部分代码
this.paramNameResolver = new ParamNameResolver(configuration, method);
}
1
2
3
4
5
6
7
8
9
10
11
12
ParamNameResolver代码介绍:

  1. 先遍历所有不是RowBounds或者ResultHandler子类的参数
  2. 先判断参数中是否存在@Param注解,存在的话hasParamAnnotation设置true
  3. 将有@Param注解的参数的值赋予name
  4. 没有注解的将会判断isUseActualParamName是否为true[1],如果不设置java编译保留参数的话,将默认为arg0,arg1…argn,设置的话为参数本身名称。
  5. 如果是false,将得到当前names的大小,设为其值0,1,2,3,4…n。最后将参数位置和名字保存在SortedMap->names中。
    举例:
    public User getUserByNameAndDep(@Param(“name”)String name,String dep);
    处理完之后names为:
    如果是3.4.1以及之后版本,isUseActualParamName设置为true,且编译开关打开

0->name
1->dep
如果是3.4.1以及之后版本,isUseActualParamName设置为true,且编译开关未打开

0->name
1->arg1
如果是3.4.1以及之后版本,isUseActualParamName设置为false,或者是3.4.1之前版本

0->name
1->1
注意:索引位置为key,名字相同也不出错,后续的程序将会覆盖,比如:
public User getUserByNameAndDep(@Param(“dep”)String name,String dep);
如果是3.4.1以及之后版本,isUs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值