请问mybatis-generator怎么自动生成mapper接口方法的实现?

在网上找过了,只能生成实体类,mapper接口,xml,请问怎么生成接口方法的实现,还是说没有这个功能?

阅读 7k
4 个回答

在generatorConfig.xml中设置了通用Mapper(或者自定义的Mapper继承了此通用Mapper)
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">

        <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>

</plugin>
mybatis-generator自动生成的Mapper会自动继承在这里设置的Mapper,tk.mybatis.mapper.common.Mapper包含了所有基本的单表的CRUD的实现,可以直接调用无需自己写接口实现,当需要继续多表操作的时候,可以自己在接口中加方法并实现和普通的mybatis一样的用法。

mybatis不需要实现Mapper接口,mybatis框架有个binding模块,会生成代理来实现Mapper接口。

mybatis的mapper是通过动态代理来实现的。
关于动态代理的API文档:https://docs.oracle.com/javas...
动态代理类顾名思义即是JVM在运行时动态产生的一个新类,具体可以查阅相关文档。
mybatis中由MapperProxyFactory产生mapper类和实例:

public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  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<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}

MapperProxy实现InvocationHandler了(此处mapperProxy并非提问所说的mapper接口的代理类,真正的代理类和实例是在MapperProxyFactory中产生的):

class MapperProxy implements InvocationHandler, Serializable {
    ...
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

  ...
}

具体的执行是在这里:
final MapperMethod mapperMethod = cachedMapperMethod(method);
mapperMethod.execute(sqlSession, args);

有session和映射的sql语句,即可完成执行一个语句的动作。

详细可以看这篇blog: Mybais之mapperproxy
关于动态代理延伸阅读:
Java 动态代理机制分析及扩展,第 1 部分
Java 动态代理机制分析及扩展,第 2 部分

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题