小米面试官:Mybatis 接口 Mapper 内的方法为啥不能重载吗?我直接懵逼了~

沙海 2021年7月3日10:43:15Java评论35字数 4607阅读15分21秒阅读模式
摘要

智能摘要

智能摘要文章源自JAVA秀-https://www.javaxiu.com/36492.html

接下来我们看看如何使用动态代理之投鞭断流,实现实例化接口并调用接口方法返回数据的。上面代码中的target,在执行Object.java内的方法时,target被指向了this,target已经变成了傀儡、象征、占位符。文章源自JAVA秀-https://www.javaxiu.com/36492.html

原文约 1969 | 图片 3 | 建议阅读 4 分钟 | 评价反馈文章源自JAVA秀-https://www.javaxiu.com/36492.html

小米面试官:Mybatis 接口 Mapper 内的方法为啥不能重载吗?我直接懵逼了~

程序员闪充宝 文章源自JAVA秀-https://www.javaxiu.com/36492.html

收录于话题文章源自JAVA秀-https://www.javaxiu.com/36492.html

#程序员闪充宝8文章源自JAVA秀-https://www.javaxiu.com/36492.html

#经验分享11文章源自JAVA秀-https://www.javaxiu.com/36492.html

#ORM2文章源自JAVA秀-https://www.javaxiu.com/36492.html

小米面试官:Mybatis 接口 Mapper 内的方法为啥不能重载吗?我直接懵逼了~文章源自JAVA秀-https://www.javaxiu.com/36492.html

作者:祖大俊文章源自JAVA秀-https://www.javaxiu.com/36492.html

来源:https://my.oschina.net/zudajun/blog/666223文章源自JAVA秀-https://www.javaxiu.com/36492.html

动态代理的功能:通过拦截器方法回调,对目标target方法进行增强。文章源自JAVA秀-https://www.javaxiu.com/36492.html

言外之意就是为了增强目标target方法。上面这句话没错,但也不要认为它就是真理,殊不知,动态代理还有投鞭断流的霸权,连目标target都不要的科幻模式。文章源自JAVA秀-https://www.javaxiu.com/36492.html

注:本文默认认为,读者对动态代理的原理是理解的,如果不明白target的含义,难以看懂本篇文章,建议先理解动态代理。文章源自JAVA秀-https://www.javaxiu.com/36492.html

1. 自定义JDK动态代理之投鞭断流实现自动映射器Mapper

首先定义一个pojo。文章源自JAVA秀-https://www.javaxiu.com/36492.html

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; } // getter setter}

再定义一个接口UserMapper.java。文章源自JAVA秀-https://www.javaxiu.com/36492.html

public interface UserMapper { public User getUserById(Integer id); }

接下来我们看看如何使用动态代理之投鞭断流,实现实例化接口并调用接口方法返回数据的。文章源自JAVA秀-https://www.javaxiu.com/36492.html

自定义一个InvocationHandler。文章源自JAVA秀-https://www.javaxiu.com/36492.html

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class MapperProxy implements InvocationHandler { @SuppressWarnings("unchecked") public <T> T newInstance(Class<T> 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 {    // 诸如hashCode()、toString()、equals()等方法,将target指向当前对象this    return method.invoke(this, args);   } catch (Throwable t) {   }  }  // 投鞭断流  return new User((Integer) args[0], "zhangsan", 18); }}

上面代码中的target,在执行Object.java内的方法时,target被指向了this,target已经变成了傀儡、象征、占位符。在投鞭断流式的拦截时,已经没有了target。文章源自JAVA秀-https://www.javaxiu.com/36492.html

写一个测试代码:文章源自JAVA秀-https://www.javaxiu.com/36492.html

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:文章源自JAVA秀-https://www.javaxiu.com/36492.html

ID:1001Name:zhangsanAge:18x.y.MapperProxy@6bc7c054

这便是Mybatis自动映射器Mapper的底层实现原理。文章源自JAVA秀-https://www.javaxiu.com/36492.html

可能有读者不禁要问:你怎么把代码写的像初学者写的一样?没有结构,且缺乏美感。文章源自JAVA秀-https://www.javaxiu.com/36492.html

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

2. Mybatis自动映射器Mapper的源码分析

首先编写一个测试类:文章源自JAVA秀-https://www.javaxiu.com/36492.html

    public static void main(String[] args) {  SqlSession sqlSession = MybatisSqlSessionFactory.openSession();  try {   StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);   List<Student> students = studentMapper.findAllStudents();   for (Student student : students) {    System.out.println(student);   }  } finally {   sqlSession.close();  } }

Mapper长这个样子:文章源自JAVA秀-https://www.javaxiu.com/36492.html

public interface StudentMapper { List<Student> findAllStudents(); Student findStudentById(Integer id); void insertStudent(Student student);}

org.apache.ibatis.binding.MapperProxy.java部分源码。文章源自JAVA秀-https://www.javaxiu.com/36492.html

public class MapperProxy<T> implements InvocationHandler, Serializable {  private static final long serialVersionUID = -6424540398559729838L;  private final SqlSession sqlSession;  private final Class<T> mapperInterface;  private final Map<Method, MapperMethod> methodCache;  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> 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部分源码。文章源自JAVA秀-https://www.javaxiu.com/36492.html

public class MapperProxyFactory<T> {  private final Class<T> mapperInterface;  @SuppressWarnings("unchecked")  protected T newInstance(MapperProxy<T> mapperProxy) {    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);  }

这便是Mybatis使用动态代理之投鞭断流文章源自JAVA秀-https://www.javaxiu.com/36492.html

3. 接口Mapper内的方法能重载(overLoad)吗?(重要)

类似下面:文章源自JAVA秀-https://www.javaxiu.com/36492.html

public User getUserById(Integer id);public User getUserById(Integer id, String name);

Answer:不能。文章源自JAVA秀-https://www.javaxiu.com/36492.html

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

SpringBoot实现登录拦截器(实战版)一个链接泄露这么多隐私,你还敢拼多多助力吗?一款零注解API接口文档生成工具Java程序员必会的工具库,让你代码量减少90%!遍历 HashMap 的5种最佳方式,以后不要乱用了!SpringCloud+Docker+Jenkins+GitLab+Maven实现自动化构建与部署实战终于明白 Java 为什么要加 final 关键字了!一款基于 Spring Boot 的BBS系统,APP和后台管理齐全,拿来即用(附项目地址)
文章源自JAVA秀-https://www.javaxiu.com/36492.html

阅读原文文章源自JAVA秀-https://www.javaxiu.com/36492.html

继续阅读
速蛙云 - 极致体验,强烈推荐!!!购买套餐就免费送各大视频网站会员!快速稳定、独家福利社、流媒体稳定解锁!速度快,全球上网、视频、游戏加速、独立IP均支持!基础套餐性价比很高!这里不多说,我一直正在使用,推荐购买:https://www.javaxiu.com/59919.html
weinxin
资源分享QQ群
本站是JAVA秀团队的技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定