MapperProxy.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!OBJECT_METHODS.contains(method.getName())) {
final Class<?> declaringInterface = findDeclaringInterface(proxy, method);//获取所有需要处理sql的接
final MapperMethod mapperMethod = new MapperMethod(declaringInterface, method, sqlSession);//构造注入
final Object result = mapperMethod.execute(args);//具体返回代理对象
if (result == null && method.getReturnType().isPrimitive() && !method.getReturnType().equals(Void.TYPE)) {
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;
}
private Class<?> findDeclaringInterface(Object proxy, Method method) {
Class<?> declaringInterface = null;
for (Class<?> iface : proxy.getClass().getInterfaces()) {
try {
Method m = iface.getMethod(method.getName(), method.getParameterTypes());
if (declaringInterface != null) {
throw new BindingException("Ambiguous method mapping. Two mapper interfaces contain the identical method signature for " + method);
} else if (m != null) {
declaringInterface = iface;
}
} catch (Exception e) {
// Intentionally ignore.
// This is using exceptions for flow control,
// but it's definitely faster.
}
}
if (declaringInterface == null) {
throw new BindingException("Could not find interface with the given method " + method);
}
return declaringInterface;
}
@SuppressWarnings("unchecked")
//mapperInterface为接口,sqlsession为包含配置xml的
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);//获取代理对象
}
调用的MapperMethod,具体相当于注入代理对象的方法实现
//c初始化
public MapperMethod(Class<?> declaringInterface, Method method, SqlSession sqlSession) {
paramNames = new ArrayList<String>();
paramPositions = new ArrayList<Integer>();
this.sqlSession = sqlSession;
this.method = method;
this.config = sqlSession.getConfiguration();
this.hasNamedParameters = false;
this.declaringInterface = declaringInterface;
setupFields();
setupMethodSignature();
setupCommandType();
validateStatement();
}
//具体执行,返回获取能够执行sql的代理对象
public Object execute(Object[] args) {
Object result = null;
if (SqlCommandType.INSERT == type) {
Object param = getParam(args);
result = sqlSession.insert(commandName, param);
} else if (SqlCommandType.UPDATE == type) {
Object param = getParam(args);
result = sqlSession.update(commandName, param);
} else if (SqlCommandType.DELETE == type) {
Object param = getParam(args);
result = sqlSession.delete(commandName, param);
} else if (SqlCommandType.SELECT == type) {
if (returnsVoid && resultHandlerIndex != null) {
executeWithResultHandler(args);
} else if (returnsList) {
result = executeForList(args);
} else if (returnsMap) {
result = executeForMap(args);
} else {
Object param = getParam(args);
result = sqlSession.selectOne(commandName, param);
}
} else {
throw new BindingException("Unknown execution method for: " + commandName);
}
return result;
}
期间MapperMethod进行匹配(即接口与xml namespace下指定操作),但是为什么可以获取xml文件的配置呢?这时候Configuration这个类就出现了,是可以解析配置文件的内容的,所以可以注入相关的指令和sql语句,在封装好下的底层进行实现,我感觉这就是为什么sqlsession是可以完全控制配置文件里面的所有sql操作的原因,而且这一步是在sqlsssionFactory完成的,但是为什么由sqlsession.getMapper(xxx.class)获取的DAO操作类却只能操作接口定义的类?第一,最简单顾名思义,DAO操作类实现接口而已,而我们自己写的代码确实没有对其进行扩充,其实扩充了,但是没有写在配置文件,还是一回事;第二,在getMapper()里面,我们是以某个接口作为参数的,参考
DefaultSqlSession.class
public <T> T getMapper(Class<T> type) {
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) {
if (!knownMappers.contains(type))
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
try {
return MapperProxy.newMapperProxy(type, sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
从上面的代码,我感觉是你单个接口,对吧,首先已经有sqlsession代理对象了,已经能够进行所有操作了,现在是通过getMapper方法获取一个DAO对象,其实还是动态代理的DAO,只不过这次是单个接口,而接口里并没有定义sql操作其他的方法,对吧,所以代理的对象只能进行这些操作了,走的class流程还是跟sqlsession代理对象产生时差不多,或许说在sqlsession里面已经有了所有xml的代理对象,但是我估计底层实现不可行的,因为,得时刻保存在内存里面,还不如构造一个通用的sqlsession,需要去的时候临时把对应的操作方法集合构造代理对象,这样比较科学。这一块我没怎么看明白哈!
以上就是我对mybatis获取SqlSession和DAO操作具体实现的一些简单认识,并且我回继续往下看!
此博客主要用于记录个人学习内容和梳理整体知识,若有许多不明和错误的地方,还请指出
,若是其他方面,概不欢迎
!
动态代理演示代码
1接口
public interface Name {
public void sayHello(String nusername);
}
2实现接口类
public class Proxyclass implements Name{
public void sayHello(String username) {
// TODO Auto-generated method stub
System.out.println(username);
}
}
3.实现动态代理
public class ProxyName implements InvocationHandler{
private Object proxied;
ProxyName(Object proxied){
this.proxied=proxied;
}
public Object invoke(Object proxy, Method method, Object[] params)
throws Throwable {
// TODO Auto-generated method stub
System.out.println(proxy.getClass().getName()+":"+method+":"+params[0]);
System.out.println(method.getName());
return(method.invoke(proxied, params));
}
}
4.测试
public class DynamicProxyDemo {
public static void main(String args[]) {
Proxyclass pro = new Proxyclass();
pro.sayHello("yaoge22");
Name name = (Name) Proxy.newProxyInstance(Name.class.getClassLoader(),
new Class[] { Name.class }, new ProxyName(pro));
name.sayHello("hello");
}
}