For MyBatisThe owned Lazy Load (Have Chinese translation into deferred loading)function, should be very classmate have heard, today mainly with everyone to read MyBatisIn the Lazy LoadThe code for the implementation of the feature. Lazy LoadThe implementation of the function is very good , that is, when the data and the object Mapping operation , only when the object is really used to do Mapping operations to reduce unnecessary database query overhead, Thus improving the efficiency of the program.
Start with the configuration section.(This article is based on the Mybatis-3.0.5 version of the source Code analysis )
in the configurationSqlsessionfactorybean, you need to specifyconfiglocationproperty, you need to setMybatis Configurationthe configuration information for the object, which has a configuration item namedlazyloadingenabledis the setting property that is used to turn on or offMybatis lazy Load < Span style= "Background-color: #ffffff;" > function. The default setting is false. Can you take a look at Sqlmap-config.xml file contents.
sqlmap-config.xml sqlsessionfactorybean org.apache.ibatis.session.configuration
class setlazyloadingenabled The implementation of the method can also be very clear analysis, Mybatis function is the need to use Cglib
Next, according to the previous talk to everyone lazy LoadThe meaning,provide its solution to thedata and objects areMappingwhen the operation is loaded, the optimization is found, as long as the MyBatis is found how to Mapping The data set with the Bo object The implementation of the operation should be able to locate how this property is to start the lazy Load feature .
MybatisThe mapping handleresultsets method to complete. and Mybatis There is only one class that implements this interface fastresultsethandler.fastresultsethandler handleresultsets
Here you can directly find the implementation of the code focus,Fastresultsethandler provides a way to implement a row of records into the function of the object.
Keep looking at the createresultobject method .
From the above code, it can be very clear to find resultobjectproxy. Createproxy is the proxy implementation of the Bo object. Finally, if we find the proxy callback implementation (Callback), we can analyze the implementation function of the final lazy Load . Inside the analysis of the positioning process will not speak, and eventually will find the Enhancedresultobjectproxyimpl class. The Intercept method is the code of the final implementation that we want to analyze. When the method of the Bo object is called, it touches the need to implement whether to load the lazy load mode.
lazyloader Save the number of attribute lists that you want to delay loading.
Lazyloader. Loadall will trigger the Resultloader Loadresult method to complete the loading implementation of the data.
so mybatislazy loadbocglibbobo
Mybatis Laz-load Function Implementation Code Appreciation (original)