Mybatis3.3.x技术内幕(二):动态代理之投鞭断流(自动映射器Mapper的底层实现原理)

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

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


动态代理的功能:经过拦截器方法回调,对目标target方法进行加强。数据库

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

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

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

首先定义一个pojo。app

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。ide

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

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

自定义一个InvocationHandler。学习

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。
测试

写一个测试代码:

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:

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

这即是Mybatis自动映射器Mapper的底层实现原理。

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

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

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

首先编写一个测试类:

    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长这个样子:

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

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

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部分源码。

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使用动态代理之投鞭断流

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

相似下面:

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)。


注:学习时,是先研究的源码,看懂了原理。写博文时,则先阐释原理,再阅读的源码。顺序恰好相反,但愿读者不要所以疑惑,觉得我强大到未卜先知。


版权提示:文章出自开源中国社区,若对文章感兴趣,可关注个人开源中国社区博客(http://my.oschina.net/zudajun)。(通过网络爬虫或转载的文章,常常丢失流程图、时序图,格式错乱等,仍是看原版的比较好)

相关文章
相关标签/搜索