在网上找过了,只能生成实体类,mapper接口,xml,请问怎么生成接口方法的实现,还是说没有这个功能?
在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是通过动态代理来实现的。
关于动态代理的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 部分
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
生产的mapper接口有继承tk.mybatis.mapper.common.Mapper,常用操作都已经有了,不需要在xml中写实现。
可以参考:http://blog.csdn.net/isea533/...
还有:https://github.com/abel533/My...