1. The principle of level two caching
As described earlier, the level two cache in MyBatis is the mapper level of caching, it is worth noting that different mapper have a level two cache, that is, the different mapper between the two-level cache is not affected by each other. To more clearly describe the level two cache, let's look at one:
Can be seen:
- SqlSession1 to query User ID 1, the query data will be stored in the Usermapper two level cache.
- If SqlSession3 executes the same mapper under SQL and commits commits, it empties the data for the level two cache area under the Usermapper.
- SqlSession2 to query the user ID 1 user information, go to the cache to find out if there is data, if there is directly from the cache to remove data.
The caching principle is similar to the first-level cache mentioned earlier, and the two-level cache differs from the first-level cache in that the two-level cache is larger in scope, and multiple sqlsession can share a two-level cache area in a mapper. How does MyBatis differentiate between the two-level cache areas of different mapper? It is differentiated according to different mapper, that is to say, if the namespace of two mapper is the same, even two mapper, then the data that executes SQL query in these two mapper will also exist in the same two-level cache area.
2. Use of level two cache
Having understood the principle of the level two cache in MyBatis, the next step is how to use level two caching. Before using it, you must first turn on the two-level cache switch.
2.1 Turn on level two cache
Since Mybaits's level two cache is the Mapper range level, the level two cache is turned on in the specific mapper.xml, in addition to the total switch to the level two cache in Sqlmapconfig.xml. Settings are as follows:
This is set in Sqlmapconfig.xml, and it has to be set in the specific Mapper.xml, as follows:
As you can see, there is only one label in the specific mapper, <cache>
and nothing is configured because there is a default implementation in MyBatis, and if we do not configure it, then the default implementation is used by default. In MyBatis's core package there is the cache interface and this default implementation, I cut a graph:
So understand, why not use the configuration can be used, MyBatis is only this default implementation class, if you do not use the MyBatis default level two cache, you need to implement the cache interface, And then in the Mapper.xml configuration, about this I'm going to talk about this, now the level two cache to use up!
2.2 Implementing the Serializable interface for the PO class
After you turn on the level two cache, you also need to implement the serializable interface to cache the Pojo, in order to take the cache data out of the deserialization operation, because the two-level cache data storage media are various, not necessarily only in memory, there may be a hard disk, if we want to take this cache again, It needs to be deserialized. So it is recommended that the Pojo in MyBatis to implement serializable interface. The following takes the user as an example to intercept a diagram:
2.3 Testing The MyBatis level two cache
@Test Public void TestCache2()throwsException {sqlsession sqlSession1 = sqlsessionfactory.opensession (); Sqlsession SqlSession2 = Sqlsessionfactory.opensession (); Sqlsession SqlSession3 = Sqlsessionfactory.opensession ();//Create proxy objectUsermapper userMapper1 = Sqlsession1.getmapper (Usermapper.class);//First initiate request, query user with ID 1User user1 = Usermapper1.finduserbyid (1); System.out.println (user1);//Perform close operation here, write data in sqlsession to level two cache areaSqlsession1.close ();//sqlsession3 is used to empty the cache, if you want to test the level two cache, you need to comment out the section //Use SqlSession3 to perform a commit () operationUsermapper UserMapper3 = Sqlsession3.getmapper (Usermapper.class); User user = Usermapper3.finduserbyid (1); User.setusername ("Nu Shen WU"); Usermapper3.updateuser (user);//Execute commit, empty the level two cache below UsermapperSqlsession3.commit (); Sqlsession3.close (); Usermapper userMapper2 = Sqlsession2.getmapper (Usermapper.class);//Second initiation request, query for user with ID 1User user2 = Usermapper2.finduserbyid (1); System.out.println (User2); Sqlsession2.close ();}
Let's first comment out the SqlSession3 section to test the results of the level two cache:
When we add the SqlSession3 section, we test the results of level two cache:
Here, we understand the implementation principle of the level two cache in MyBatis, which is a bit like hibernate. You can also look at the blog post I wrote about Hibernate's level two cache (although it is recommended to read the Ehcache section below and then control Hibernate).
2.4 Other configurations (UseCache and Flushcache)
Configuration items such as Usercache and Flushcache can also be configured in MyBatis, Usercache is used to set whether to disable level two cache , set statement in usecache= False to disable the level two cache for the current SELECT statement, that is, each query emits a SQL query, which by default is true, that is, the SQL uses a level two cache.
<select id="findOrderListResultMap" resultMap="ordersUserMap" useCache="false">
This is the case for each query requires the latest data SQL, to be set to Usecache=false, disable level two cache, directly from the database to get.
In the same namespace of mapper, if you have additional insert, UPDATE, delete operation data, you need to flush the cache, and dirty reads will occur if you do not perform a flush cache. Sets the Flushcache= "true" property in the statement configuration, which is true by default, which refreshes the cache and does not refresh if it is changed to false. When you use caching, dirty reads occur if you manually modify the query data in a database table.
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User" flushCache="true">
In general, the commit operation will need to flush the cache, flushcache=true means to flush the cache, which avoids the database dirty read. So we don't have to set it, by default, here is just a mention.
3. MyBatis Integrated Ehcache distributed Cache Framework
3.1 The origin of the problem
The above section mainly summarizes the use of the level two cache in MyBatis, but the default two level cache in the MyBatis has a disadvantage, that is, the distributed cache can not be implemented, what does it mean? That is, the cached data on its own server, assuming that there are now two servers A and B, the user access to the a server, the query after the cache will be placed on a server, assuming that there is a user access to the B server, then he on the B server can not get just that cache, as shown in:
So in order to solve this problem, we need to find a distributed cache, specifically used to store the cached data, so that the different servers to cache the data to be stored in it, and take the cache data from it, as shown in:
This solves the problem mentioned above, in order to improve the system concurrency performance, we generally do the above distributed deployment (cluster deployment mode), so we want to use distributed cache to centrally manage the cached data. However, MyBatis cannot implement distributed caching and needs to be integrated with other distributed cache frameworks, which are mainly about Ehcache.
3.2 Integration Methods
As mentioned earlier, MyBatis provides a cache interface that implements the cache interface development if it is to implement its own caching logic. The MyBatis itself is implemented by default, but the implementation of this cache does not implement distributed caching, so we have to implement it ourselves. Ehcache distributed cache is available, MyBatis provides a Ehcache implementation class for the cache interface, which is in the integration package for MyBatis and Ehcache. So first we need to import the integration package (click I download).
After the jar package has been imported, configure the type of cache in the Mapper to be the implementation type of the Ehcache to the cache interface. Ehcache has an implementation class for the cache interface:
We will write the fully qualified name of the class to the type attribute, as follows:
OK, the configuration is complete, now MyBatis will automatically execute the Ehcache implementation class, will not use their own default level two cache, but using Ehcache also has a cache configuration do not forget to create a new Ehcache.xml file under Classpath:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi: noNamespaceSchemaLocation=". /config/ehcache.xsd "> <diskstore path="F:\develop\ehcache"/> <defaultcache maxElement Sinmemory = "10000" eternal = "false" timetoidleseconds = "1 " timetoliveseconds =" + " maxelementsondisk = "10000000" diskexpirythreadintervalseconds = " memorystoreevictionpolicy =; <persistence Strategy="Localtempswap"/> </defaultcache></ehcache>
The function of this configuration is similar to hibernate, so you can refer to my blog post of hibernate level two cache. Next is the test, or use the above test program, because only to change the cache, the other did not move. So far, MyBatis's level two cache is almost finished.
4. Application scenarios and limitations of level two caching
For access to many query requests and users of query results real-time requirements are not high, at this time can use MyBatis two cache technology to reduce database access, improve access speed, business scenarios such as: time-consuming statistical analysis of SQL, telephone Bill query SQL. The implementation is as follows: By setting the refresh interval, the cache is automatically emptied by mybatis at intervals, and the cache refresh interval is set according to the data change frequency flushinterval, for example, set to 30 minutes, 60 minutes, 24 hours, etc., depending on the needs.
MyBatis level Two cache for fine-grained data-level cache implementation is not good, such as the following requirements: The product information cache, because the product information query access is large, but require users every time can query the latest product information, At this point, if you use MyBatis's level two cache, you cannot realize that when a commodity changes, only the cache information of the product is refreshed and the information of other goods is not refreshed, because Mybaits's level two cache area is divided by mapper, and when an item information changes, the cached data of all commodity information is emptied. Addressing such issues may require a targeted cache of data on demand at the business level.
Related reading: http://blog.csdn.net/column/details/smybatis.html
Learning Note Source: Https://github.com/eson15/MyBatis_Study
-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15
Level two cache in "MyBatis Learning 13" MyBatis