引言
最近刚写完毕设,闲来无事,看到网上有一个手撸Mybatis的教程,于是想自己实现一个简易版的Mybatis。
本专栏的源码:https://gitee.com/dhi-chen-xiaoyang/yang-mybatis。
创建简单的映射器代理工厂
在使用mybatis的时候,我们一般只需要定义mapper的接口,并添加相应的@Mapper注解,然后实现对应的xml文件即可,而不需要对mapper接口进行具体的实现。其实本质上,这些mapper接口是有实现的,但不是我们手动通过implement来实现,而是通过代理的方式进行实现。因此,对于Mybatis的手撸,首先要关注的,就是如何对mapper进行代理。
首先我们定义一个MapperProxy,该类实现InvocationHandler接口,通过实现该接口,实现动态代理。这里有两个属性——sqlSession和mapperInterface,其中,sqlSession是用来模拟执行sql语句的。
package com.yang.mybatis.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
public class MapperProxy<T> implements InvocationHandler {
private Map<String, Object> sqlSession ;
private Class<T> mapperInterface;
public MapperProxy(Map<String, Object> sqlSession, Class<T> mapperInterface) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
String key = this.mapperInterface.getName() + "." + method.getName();
return sqlSession.get(key);
}