In the previous two MyBatis source code interpretation, we tracked to Mapperproxy, know that although the use of dynamic Proxy technology allows us to directly use the interface method. In order to consolidate and deepen dynamic agents, we may wish to recall again what is a dynamic agent.
I believe that when beginners mybatis almost everyone will issue a question, why is clearly Xxxdao interface, I do not use any code to implement this interface, but can directly use this interface method. Now it's clear that the dynamic agent. Let's write a demo applet to see.
The first is a Test.java interface , with only one say method.
1 PackageDay_16_proxy;2 3 /**4 * @authorYu Linfung5 *6 * November 16, 20167 */8 Public InterfaceTest {9 voidsay ();Ten}
We now imagine that MyBatis does not need to implement it but calls directly.
Test.say ();
Of course, it is not possible to instantiate an interface directly, it is necessary to generate a proxy class Testproxy.java, this class needs to implement the Invocationhandler interface.
1 PackageDay_16_proxy;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 6 /**7 * @authorYu Linfung8 *9 * November 16, 2016Ten */ One Public classTestproxyImplementsInvocationhandler { A - /*(Non-javadoc) - * @see Java.lang.reflect.invocationhandler#invoke (java.lang.Object, Java.lang.reflect.Method, Java.lang.Object []) the */ - @Override - Publicobject Invoke (Object proxy, Method method, object[] args) - throwsThrowable { + if(Method.getname (). Equals ("Say")){ -System.out.println ("Hello World"); + } A return NULL; at } - -}
The Invoke method needs to be implemented, meaning "invoke" (of course, we want to invoke the method in the interface and do not show invoke Invoke). We see from line 19th that when the method called is say, the output is "Hello World". With this Testproxy.java proxy class, we'll test it in the client code.
1 PackageDay_16_proxy;2 3 ImportJava.lang.reflect.Proxy;4 5 /**6 * @authorYu Linfung7 *8 * November 16, 20169 */Ten Public classClient { One A Public Static voidMain (string[] args) { -Test test = (test) proxy.newproxyinstance (test).class. getClassLoader (),NewClass<?>[]{test.class},Newtestproxy ()); - Test.say (); the } -}
In line 14th, we have been able to directly invoke the Say method in the test interface because we have generated a proxy class instance, Testproxy, by means of the Proxy.newproxyinstance method.
Back to our MyBatis source, in the previous section we learned that a DAO interface actually generated a MAPPERPROXY proxy class through Mapperproxyfactory.
1 // org.apache.ibatis.binding.MapperProxyFactory 2 protected T newinstance (mapperproxy<t> mapperproxy) {3 returnnew class[] { Mapperinterface}, Mapperproxy); 4 }
is the 3rd line of code the same as the client test code in the example at the beginning? Generate the proxy class, the proxy class is mapperproxy. It is clear how MyBatis constructs the proxy class to solve the first problem-how an interface can call its methods directly.
Now throw the second question--how does each specific method in the interface do one by one implementations of the proxy? Let's look at the Mapperproxy class again. This time we'll look at the Invocationhanlder.invoke method implemented by the Mapperproxy class.
1 //Org.apache.ibatis.binding.MapperProxy2 PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {3 if(Object.class. Equals (Method.getdeclaringclass ())) {4 Try {5 returnMethod.invoke ( This, args);6}Catch(Throwable t) {7 Throwexceptionutil.unwrapthrowable (t);8 }9 }Ten FinalMappermethod Mappermethod =Cachedmappermethod (method); One returnMappermethod.execute (sqlsession, args); A}
The 3rd line makes a judgment, judging whether it is a class, if it is a class, so long direct transfer method and parameter call can. But we know that this is an interface (you can also implement the interface yourself, as the old version usually does). If it is not a class, a Mappermethod method is created. See the idea: It seems that this class is executing every interface method we call. Finally, the Mappermethod.execute method is returned. Temporarily disregard the Cachedmappermethod method in the Mapperproxy class.
Take a look at the Mappermethod class, this Mappermethod class is very awesome ah, it can be said that it is to rule all the database and the method of dealing with (of course, only insert, delete, UPDATE, select Four methods). So, no matter how many methods your DAO layer has, it boils down to SQL statements that have only insert, delete, update, select, and you can expect to first determine what SQL statement is in Mappermethod's Execute method.
// Org.apache.ibatis.binding.MapperMethod Public Object Execute (sqlsession sqlsession, object[] args) { switch (Command.gettype ()) { Case INSERT: {...} Case UPDATE: {...} Case DELETE: {...} Case SELECT: {...} Case FLUSH: {... }}}
This is a limitation of the Meppermethod.execute method, and we can see exactly what SQL statements are first judged inside the Execute method. (Note: In reading this part of the source code, our main line is how MyBatis creates a proxy class, and implements its methods, and temporarily ignores the details)
We select the common "select" SQL statement to interpret, and in the "select" statement will be designed to more detail problems:
1 //org.apache.ibatis.binding2 CaseSELECT:3 if(Method.returnsvoid () &&Method.hasresulthandler ()) {4 Executewithresulthandler (sqlsession, args);5result =NULL;6}Else if(Method.returnsmany ()) {7result =Executeformany (sqlsession, args);8}Else if(Method.returnsmap ()) {9result =Executeformap (sqlsession, args);Ten}Else if(Method.returnscursor ()) { Oneresult =executeforcursor (sqlsession, args); A}Else { -Object param =Method.convertargstosqlcommandparam (args); -result =Sqlsession.selectone (Command.getname (), param); the } - Break;
Let's take a try by selecting the method in the Executeformany in line 7th.
1 //Org.apache.ibatis.binding.MapperMethod2 Private<E>Object Executeformany (sqlsession sqlsession, object[] args) {3List<e>result;4Object param =Method.convertargstosqlcommandparam (args);5 if(Method.hasrowbounds ()) {6Rowbounds rowbounds =method.extractrowbounds (args);7result = Sqlsession.<e>SelectList (Command.getname (), param, rowbounds);8}Else {9result = Sqlsession.<e>SelectList (Command.getname (), param);Ten } One //issue #510 Collections & Arrays Support A if(!Method.getreturntype (). IsAssignableFrom (Result.getclass ())) { - if(Method.getreturntype (). IsArray ()) { - returnConverttoarray (result); the}Else { - returnconverttodeclaredcollection (Sqlsession.getconfiguration (), result); - } - } + returnresult; -}
Lines 7th and 9th are where we actually execute the SQL statement, and it turns back to the Sqlsession method. In the next section, we'll go back to the important sqlsession.
MyBatis Source code Interpretation (3)--mappermethod