MyBatis实现原理:动态代理的运用

动态代理的功能:

  • 通过拦截器方法回调,对目标target方法进行增强。
  • 动态代理还有”投鞭断流“的霸权,连目标target都不要的使用方式。

自动映射器Mapper自己实现

定义pojo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.justxzm.proxy;

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
}

定义接口

1
2
3
4
5
package com.justxzm.proxy;

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

定义代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.justxzm.proxy;

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);
}
}

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.justxzm.proxy;

public class MyTest {

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());
}
}
1
2
3
4
ID:1001
Name:zhangsan
Age:18
com.justxzm.proxy.MapperProxy@66788a7b

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

自动映射器Mapper源码分析

编写一个测试类

1
2
3
4
5
6
7
8
9
10
11
12
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接口

1
2
3
4
5
public interface StudentMapper {
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}

MapperProxy.java

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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);
}
// ...

MapperProxyFactory.java

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

1
2
3
4
5
6
7
8
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使用动态代理之投鞭断流。

问题(重要)

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

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

0%