Mybatis接口Mapper内的方法为啥不能重载?

Mybatis接口Mapper内的方法为啥不能重载?

> 公众号:[Java小咖秀](https://t.1yb.co/jwkk),网站:[javaxks.com](https://www.javaxks.com)

> 作者: 祖大俊 ,来源:https://my.oschina.net/zudajun/blog/666223

声明一个 interface 接口,没有任何实现类,却要求实例化接口对象,并能调用接口方法返回业务数据,老一辈 IT 革命家给出评论:这简直是无 -- 稽 --- 之谈。

一日小区漫步,我问朋友:Mybatis 中声明一个 interface 接口,没有编写任何实现类,Mybatis 就能返回接口实例,并调用接口方法返回数据库数据,你知道为什么不?朋友很是诧异:是啊,我也很纳闷,我们领导告诉我们按照这个模式编写就好了,我同事也感觉很奇怪,虽然我不知道具体是怎么实现的,但我觉得肯定是……(此处略去若干的漫天猜想),但是也不对啊,难道是……(再次略去若干似懂非懂)。

这激发了我写本篇文章的冲动。

动态代理的功能:通过拦截器方法回调,对目标 target 方法进行增强。

言外之意就是为了增强目标 target 方法。上面这句话没错,但也不要认为它就是真理,殊不知,动态代理还有投鞭断流的霸权,连目标 target 都不要的科幻模式。

注:本文默认认为,读者对动态代理的原理是理解的,如果不明白 target 的含义,难以看懂本篇文章,建议先理解动态代理。

1. 自定义 JDK 动态代理之投鞭断流实现自动映射器 Mapper首先定义一个 pojo。

代码语言:javascript复制public class User {

private Integer id;

private String name;

private int age;

public User(Integer id, String name, int age) {

this.id = id;

this.name = name;

this.age = age;

}

}再定义一个接口 UserMapper.java。

代码语言:javascript复制public interface UserMapper {

public User getUserById(Integer id);

}接下来我们看看如何使用动态代理之投鞭断流,实现实例化接口并调用接口方法返回数据的。

自定义一个 InvocationHandler。

代码语言:javascript复制import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

public class MapperProxy implements InvocationHandler {

@SuppressWarnings("unchecked")

public T newInstance(Class clz) {

return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[] { clz }, this);

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

if (Object.class.equals(method.getDeclaringClass())) {

try {

return method.invoke(this, args);

} catch (Throwable t) {

}

}

return new User((Integer) args[0], "zhangsan", 18);

}

}上面代码中的 target,在执行 Object.java 内的方法时,target 被指向了 this,target 已经变成了傀儡、象征、占位符。在投鞭断流式的拦截时,已经没有了 target。

写一个测试代码:

代码语言:javascript复制public static void main(String[] args) {

MapperProxy proxy = new MapperProxy();

UserMapper mapper = proxy.newInstance(UserMapper.class);

User user = mapper.getUserById(1001);

System.out.println("ID:" + user.getId());

System.out.println("Name:" + user.getName());

System.out.println("Age:" + user.getAge());

System.out.println(mapper.toString());

}output:

代码语言:javascript复制ID:1001

Name:zhangsan

Age:18

x.y.MapperProxy@6bc7c054这便是 Mybatis 自动映射器 Mapper 的底层实现原理。

可能有读者不禁要问:你怎么把代码写的像初学者写的一样?没有结构,且缺乏美感。

必须声明,作为一名经验老道的高手,能把程序写的像初学者写的一样,那必定是高手中的高手。这样可以让初学者感觉到亲切,舒服,符合自己的 Style,让他们或她们,感觉到大牛写的代码也不过如此,自己甚至写的比这些大牛写的还要好,从此自信满满,热情高涨,认为与大牛之间的差距,仅剩下三分钟。

2. Mybatis 自动映射器 Mapper 的源码分析首先编写一个测试类:

代码语言:javascript复制 public static void main(String[] args) {

SqlSession sqlSession = MybatisSqlSessionFactory.openSession();

try {

StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

List students = studentMapper.findAllStudents();

for (Student student : students) {

System.out.println(student);

}

} finally {

sqlSession.close();

}

}Mapper 长这个样子:

代码语言:javascript复制public interface StudentMapper {

List findAllStudents();

Student findStudentById(Integer id);

void insertStudent(Student student);

}org.apache.ibatis.binding.MapperProxy.java 部分源码。

代码语言:javascript复制public class MapperProxy implements InvocationHandler, Serializable {

private static final long serialVersionUID = -6424540398559729838L;

private final SqlSession sqlSession;

private final Class mapperInterface;

private final Map methodCache;

public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {

this.sqlSession = sqlSession;

this.mapperInterface = mapperInterface;

this.methodCache = methodCache;

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

if (Object.class.equals(method.getDeclaringClass())) {

try {

return method.invoke(this, args);

} catch (Throwable t) {

throw ExceptionUtil.unwrapThrowable(t);

}

}

final MapperMethod mapperMethod = cachedMapperMethod(method);

return mapperMethod.execute(sqlSession, args);

}org.apache.ibatis.binding.MapperProxyFactory.java 部分源码。

代码语言:javascript复制public class MapperProxyFactory {

private final Class mapperInterface;

@SuppressWarnings("unchecked")

protected T newInstance(MapperProxy mapperProxy) {

return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);

}这便是 Mybatis 使用动态代理之投鞭断流。

3. 接口 Mapper 内的方法能重载(overLoad)吗?(重要)类似下面:

代码语言:javascript复制public User getUserById(Integer id);

public User getUserById(Integer id, String name);Answer:不能。

原因:在投鞭断流时,Mybatis 使用 package+Mapper+method 全限名作为 key,去 xml 内寻找唯一 sql 来执行的。类似:key=x.y.UserMapper.getUserById,那么,重载方法时将导致矛盾。对于 Mapper 接口,Mybatis 禁止方法重载(overLoad)。

注:学习时,是先研究的源码,看懂了原理。写博文时,则先阐释原理,再阅读的源码。顺序刚好相反,希望读者不要因此疑惑,以为我强大到未卜先知。

🎨 相关创意作品

支付宝聊天怎么启用阅后即焚功能
完美体育365

支付宝聊天怎么启用阅后即焚功能

📅 07-24 👁️ 9776
怀斯曼W1160C高质量环保局批准的迷你1800千克轮式装载机1年紧凑型前装载机多功能堆芯装载机
排面!摩洛哥国王皇宫接见摩洛哥全队,为世界杯第4名颁发王室勋章