`
sxk4429
  • 浏览: 39803 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

mybatis Dao 接口 没有实现类的源码实现

阅读更多
注意:TestTable 为POJO,TestTableMapper为DAO接口,mappingXml 为sql 配置文档,专业点叫sql mapper

Mybatis 有一个调用dao的方式 ,如下:
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session= sqlMapper.openSession();
TestTableMapper t= session.getMapper(TestTableMapper.class);
TestTable tt=(TestTable)t.selectByPrimaryKey("wwww");

TestTableMapper是一个inteface,不是一个class,并且我查看了用mybatis genetator产生的code,没有该接口的实现的..冷,我当时以为我用generator产生的code有问题,可是,用上面一段code跑一下,竟然有从DB query到值. 恩,有玄机,哥哥于是准备吃点亏,翻源码来瞧瞧.

玄机就在session.getMapper()
session.getMapper()使用了代理,当调用一次此方法,都会产生一个代理class的instance,看看这个代理class的实现.
public class MapperProxy implements InvocationHandler {
...
public static <T> T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
    ClassLoader classLoader = mapperInterface.getClassLoader();
    Class<?>[] interfaces = new Class[]{mapperInterface};
    MapperProxy proxy = new MapperProxy(sqlSession);
    return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
  }

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (!OBJECT_METHODS.contains(method.getName())) {
      final Class<?> declaringInterface = findDeclaringInterface(proxy, method);
      final MapperMethod mapperMethod = new MapperMethod(declaringInterface, method, sqlSession);
      final Object result = mapperMethod.execute(args);
      if (result == null && method.getReturnType().isPrimitive()) {
        throw new BindingException("Mapper method '" + method.getName() + "' (" + method.getDeclaringClass() + ") attempted to return null from a method with a primitive return type (" +    method.getReturnType() + ").");
      }
      return result;
    }
    return null;
  }
这里是用到了JDK的代理Proxy。
newMapperProxy()可以取得实现interfaces 的class的代理类的实例,当执行interfaces中的方法的时候,会自动执行invoke()方法,其中public Object invoke(Object proxy, Method method, Object[] args)中 method参数就代表你要执行的方法.

MapperMethod类会使用method方法的methodName 和declaringInterface去取 sqlMapxml 取得对应的sql,也就是拿declaringInterface的类全名加上 sqlid..
贴一点sqlMap xml 看看..
<mapper namespace="com.whisper.dao.TestTableMapper">
   <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">

嘿嘿,总结一下,其实就是用了 jdk的代理类而已....
分享到:
评论
3 楼 yh4s 2015-11-11  
2 楼 hanson08 2015-03-20  
厉害,非常理解了。不知道有对mybatis参数映射与结果映射底层的相关讲解?
1 楼 陈颜宇 2015-01-04  
哥哥很强大

相关推荐

Global site tag (gtag.js) - Google Analytics