大致可分为如下几个步骤
MapperFactoryBean:
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
DefaultSqlSession:
public <T> T getMapper(Class<T> type) {
//configuration是mybatis的重要配置类, 在初始化的时候, 就会将mapper接口添加到configuration中
return configuration.getMapper(type, this);
}
Configuration:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
MapperRegistry:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//获取mapper代理工厂
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
MapperProxyFactory:
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
//返回一个新代理对象
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//过滤掉object的方法
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
实例对象
如有谬误, 欢迎斧正
简化版如下: https://blog.csdn.net/sinat_25991865/article/details/89891581
public interface UserMapper {
List<SysUser> selectAll();
}
public class MyMapperProxy<T> implements InvocationHandler {
private Class<T> mapperInterface;
private SqlSession sqlSession;
public MyMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
this.mapperInterface = mapperInterface;
this.sqlSession = sqlSession;
}
@Override
public Object invoke(Object proxy , Method method , Object[] args)
throws Throwable {
//针对不同的 sql 类型,需要调用sqlSession不同的方法
//接口方法中的参数也有很多情况 ,这里只考虑没有有参数的情况
List<T> list= sqlSession.selectList(
mapperInterface.getCanonicalName() + ”.” + method.getName());
//返回数据也有很多情况,这里不做处理直接返回
return list;
}
}
方法调用
//获取sqlSession
SqlSession sqlSession = getSqlSession();
//获取 UserMapper 接口
MyMapperProxy userMapperProxy = new MyMapperProxy(
UserMapper.class , sqlSession) ;
UserMapper userMapper = (UserMapper) Proxy.newProxyinstance (
Thread.currentThread().getContextClassLoader(),
new Class[ ] {UserMapper.class},
userMapperProxy) ;
//调 用 selectAll 方 法
List<SysUser> user= userMapper.selectAll();
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。