First-level caching and level two caching
MyBatis the data cache into a two-level structure, divided into a first-level cache, a level two cache:
The first-level cache is a session-level cache, located in a Sqlsession object that represents a database session, and is called a local cache. First-level caching is an internal implementation of the MyBatis, users can not configure, by default, automatically supported by the cache, the user does not customize its rights (but this is not absolute, can be modified through the development of Plug-ins);
The second-level cache is the application application-level cache, which has a long lifecycle, just like the application declaration cycle, meaning that its scope is the entire application application.
The organization of the MyBatis cache and level two caching is shown in the following illustration:
The working mechanism of the first level caching:
The first-level cache is session-level, in general, a Sqlsession object uses a Executor object to complete the session operation, and the Executor object maintains a cache buffer to improve query performance.
The working mechanism of the second-level caching:
As mentioned above, a Sqlsession object will use a Executor object to complete the session operation, the MyBatis two-level caching mechanism is the key to this executor object. If the user is configured with "Cacheenabled=true", then MyBatis adds an adorner to the Executor object when creating the Executor object for the Sqlsession object: Cachingexecutor, At this point sqlsession uses the Cachingexecutor object to complete the operation request. Cachingexecutor for a query request, it first determines whether the query request has cached results in the level two cache of application levels, returns the cached results directly if there are queries, and then gives the true executor object to complete the query operation if there is no cache. Cachingexecutor then places the results of the query returned by the real executor in the cache and returns them to the user.
MyBatis's Level Two cache is designed to be more flexible, and you can use MyBatis's own defined level two cache implementation You can also customize the cache by implementing the Org.apache.ibatis.cache.Cache interface, or you can use a third-party memory cache, such as memcached.
Cache modification
Question:
The most likely problem is when the cache is turned on, the page query will return the first page of data whenever it is queried. In addition, when you use SQL auto-generated plug-ins to generate SQL for the Get method, the incoming arguments do not work, and the query results for the first argument are returned regardless of the number of arguments passed in.
Why these problems occur:
Before explaining the implementation process of MyBatis mentioned, in the premise of opening cache, MyBatis's executor will read the data from the cache first, read the database query. The problem is that the SQL automatic generation plug-in and the paging plug-in are executed in Statementhandler, and the Statementhandler is executed after executor, regardless of whether the SQL automatic generation plug-in and the paging plug-in are implemented by overwriting SQL. Executor is used in the original SQL to generate the key that reads cache (the key is made up of SQL and corresponding parameter values), which is of course problematic.
Solve the problem:
After finding the cause of the problem, it is convenient to solve it. As long as the interceptor to rewrite the executor generated key method, when the build can be used automatically generated SQL (corresponding SQL automatically generated plug-ins) or add paging information (corresponding paging plug-ins) on it.
Interceptor Signature:
@Intercepts ({@Signature (type = Executor.class, method = "Query", args = {mappedstatement.class, object.class, Rowbounds.class, Resulthandler.class})}) Public
class Cacheinterceptor implements Interceptor {
...
}
As you can see from the signature, the target type to intercept is executor (note: type can only be configured as an interface type) and the method to intercept is the method named query.
Implementation of intercept:
Public Object intercept (invocation invocation) throws Throwable {Executor executorproxy = (Executor) invocation.get
Target (); MetaObject metaexecutor = Metaobject.forobject (Executorproxy, Default_object_factory, DEFAULT_OBJECT_WRAPPER_
FACTORY);
Detach Agent Object Chain while (Metaexecutor.hasgetter ("H")) {object = Metaexecutor.getvalue ("h");
Metaexecutor = Metaobject.forobject (object, Default_object_factory, default_object_wrapper_factory); The target class of the last proxy object, while (Metaexecutor.hasgetter ("target")) {object = Metaexecutor.getvalue ("Tar
Get ");
Metaexecutor = Metaobject.forobject (object, Default_object_factory, default_object_wrapper_factory);
} object[] args = Invocation.getargs ();
Return This.query (Metaexecutor, args); } public <E> list<e> query (MetaObject metaexecutor, object[] args) throws SQLException {Mappedstate
ment ms = (mappedstatement) args[0]; Object Parameterobject= Args[1];
Rowbounds rowbounds = (rowbounds) args[2];
Resulthandler Resulthandler = (resulthandler) args[3];
Boundsql boundsql = Ms.getboundsql (Parameterobject);
Rewrite key generation CacheKey CacheKey = Createcachekey (MS, Parameterobject, Rowbounds, Boundsql);
Executor Executor = (Executor) metaexecutor.getoriginalobject ();
Return Executor.query (MS, Parameterobject, Rowbounds, Resulthandler, CacheKey, Boundsql); Private CacheKey Createcachekey (mappedstatement MS, Object Parameterobject, Rowbounds rowbounds, Boundsql BoundSql)
{Configuration Configuration = ms.getconfiguration ();
Pagesqlid = Configuration.getvariables (). GetProperty ("Pagesqlid"); if (null = = Pagesqlid | |
'. Equals (Pagesqlid)} {Logger.warn (' property pagesqlid isn't setted,use default '. *page$ ');
Pagesqlid = Defaultpagesqlid;
} cachekey CacheKey = new CacheKey ();
Cachekey.update (Ms.getid ());
Cachekey.update (Rowbounds.getoffset ()); Cachekey.update (Rowbounds.getlimit ());
list<parametermapping> parametermappings = Boundsql.getparametermappings (); Resolves a bug where the automatically generated Sql,sql statement is empty causing the key to generate an error if (null = Boundsql.getsql () | |
'. Equals (Boundsql.getsql ())} {String id = ms.getid ();
id = id.substring (Id.lastindexof (".") + 1);
String newsql = null;
try {if ("select". Equals (ID)) {newsql = Sqlbuilder.buildselectsql (Parameterobject);
} Sqlsource Sqlsource = Buildsqlsource (Configuration, Newsql, Parameterobject.getclass ());
Parametermappings = Sqlsource.getboundsql (parameterobject). Getparametermappings ();
Cachekey.update (Newsql);
catch (Exception e) {logger.error ("Update cachekey error.", e);
} else {cachekey.update (Boundsql.getsql ()); } metaobject metaobject = Metaobject.forobject (Parameterobject, Default_object_factory, DEFAULT_OBJECT_WRAPPER_FACT
Ory); if (ParametermaPpings.size () > 0 && parameterobject!= null) {Typehandlerregistry typehandlerregistry = Ms.getconfigur
ation (). Gettypehandlerregistry ();
if (Typehandlerregistry.hastypehandler (Parameterobject.getclass ())) {cachekey.update (parameterobject); } else {for (parametermapping parametermapping:parametermappings) {String propertyname = parameter
Mapping.getproperty ();
if (Metaobject.hasgetter (PropertyName)) {Cachekey.update (Metaobject.getvalue (PropertyName)); ' Else If ' (Boundsql.hasadditionalparameter (PropertyName)) {cachekey.update (Boundsql.getadditionalparameter p
Ropertyname)); ////When paging queries are required, add the current page and pages in the page parameter to CacheKey if (Ms.getid (). Matches (Pagesqlid) && ;
Metaobject.hasgetter ("page")) {pageparameter page = (pageparameter) metaobject.getvalue ("page"); if (null!= page) {cachekey.update (Page.getcurrenTpage ());
Cachekey.update (Page.getpagesize ());
} return CacheKey;
}
Implementation of plugin:
public Object Plugin {
///when the target class is a cachingexecutor type, wrap the target class, or return the target itself directly, reducing the target being represented by
//Times
if ( Target instanceof Cachingexecutor) {return
plugin.wrap (target, this), or
else {return
target;
}