Level two cache in the "MyBatis Learning 13" MyBatis

Source: Internet
Author: User
1. The principle of level two caching

As described earlier, the level two cache in MyBatis is a mapper cache, and it is noteworthy that different mapper have a level two cache, that is to say, the two-level cache between different mapper is not mutually affected. For a clearer description of level two caching, first look at a schematic:

As can be seen from the figure: SqlSession1 to query User ID 1 user information, query to user information will be the query data stored in the Usermapper level two cache. If SqlSession3 goes to execute the same mapper SQL and commits the commit, the data in the level two cache area of the usermapper is emptied. SqlSession2 to query User ID 1 user information, to the cache to find whether there is data, if there is a direct extraction of data from the cache.

The execution of the cache is similar to the first-level cache mentioned above, the difference between level two cache and first-level cache is that the level two cache is larger, and multiple sqlsession can share a two-level cache region in a mapper. MyBatis is how to differentiate between the two-level cache regions of different mapper. It is differentiated according to different mapper with different namespace, that is, if two mapper namespace the same, even two mapper, then the data that executes SQL queries in the two mapper will also have the same level two cache area. 2. Use of level two cache

After understanding the principle of level two caching in MyBatis, the next step is how to use level two caching. Before using, you must first turn on the two-level cache switch. 2.1 Open Level two cache

Because the level two cache of Mybaits is mapper range, in addition to the total switch of level two cache in Sqlmapconfig.xml, a level two cache is opened in a specific mapper.xml. The settings are as follows:

This is set in Sqlmapconfig.xml and is set in a specific Mapper.xml, as follows:

You can see that in the specific mapper only a <cache> tag, and did not configure anything, this is because the MyBatis has the default implementation, if we do not configure, then default to use that default implementation. In MyBatis's core package there is the cache interface and this default implementation, I cut a diagram:

So understand, why not configure all can use, MyBatis only this one default implementation class, if not using MyBatis default Level two cache, you need to implement the cache interface, And then configure it in the Mapper.xml, and I'll talk about that in the next, and now I'll use the level two cache. 2.2 Implementation of the PO class serializable interface

When the level two cache is turned on, you also need to implement the serializable interface for the Pojo that will be cached, in order to deserialize the cached data, because the level two cache data storage media is diverse, not necessarily in memory, there may be a hard drive, and if we are going to take this cache again, You need to deserialize it. Therefore, it is recommended that the Pojo in MyBatis to implement the serializable interface. Take the user as an example to truncate the diagram below:
2.3 Test MyBatis's Level two cache

@Test public void TestCache2 () throws Exception {sqlsession sqlSession1 = sqlsessionfactory.opensession ();
    Sqlsession SqlSession2 = Sqlsessionfactory.opensession ();
    Sqlsession SqlSession3 = Sqlsessionfactory.opensession ();
    Create a proxy object Usermapper userMapper1 = Sqlsession1.getmapper (Usermapper.class);
    The first time the request was initiated, the user User1 = Usermapper1.finduserbyid (1) with a query ID of 1;  
    System.out.println (user1);

    The shutdown operation is performed here, and the data in the sqlsession is written to the level two cache area sqlsession1.close (); SqlSession3 is used to empty the cache, if you want to test level two cache, you need to comment out///Use SqlSession3 Execute commit () operation Usermapper UserMapper3 = Sqlsession3.getmappe
    R (Usermapper.class);
    User user = Usermapper3.finduserbyid (1);
    User.setusername ("Nu Shen Wu");
    Usermapper3.updateuser (user);
    Execute the submission, emptying the level two cache Sqlsession3.commit () below the usermapper;

    Sqlsession3.close ();
    Usermapper userMapper2 = Sqlsession2.getmapper (Usermapper.class);
    Second launch request, user User2 = Usermapper2.finduserbyid (1) with Query ID 1;
System.out.println (User2);
    Sqlsession2.close (); }

Let's start by commenting out the SqlSession3 section to test the results of the level two cache:

When we add the SqlSession3 part, we test the level two cache result:

Here, we understand the implementation of the two-level cache in MyBatis, and this is a bit like the hibernate. can also be compared to my written hibernate two-level cache blog to see (but it is recommended that the following Ehcache part of the reading and then control hibernate see). 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 caching , set statement in usecache= False disables the level two cache of the current SELECT statement, that is, each query emits SQL to query, and the default is true, that is, the SQL uses level two caching.

<select id= "Findorderlistresultmap" resultmap= "Ordersusermap" usecache= "false" >

This situation is for each query requires the latest data SQL, to set to Usecache=false, disable level two cache, directly from the database.
In the same namespace of mapper, if you have additional insert, UPDATE, delete operation data, you need to flush the cache, and dirty reads occur if you do not perform a refresh cache. Set 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. Dirty reads occur when you use caching to manually modify query data in a database table.

<insert id= "Insertuser" parametertype= "Cn.itcast.mybatis.po.User" flushcache= "true" >

In general, you need to flush the cache to perform a commit, and flushcache=true to flush the cache, which avoids database dirty reading. So we don't have to set, the default can be, here is just a mention. 3. MyBatis Integrated Ehcache distributed caching 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 MyBatis has a disadvantage, that is, the implementation of distributed caching, what does it mean. This means that the cached data is on its own server, assuming that there are now two servers A and B, user access to a server, the query after the cache will be placed on a server, assuming that there is a user to access the B server, then he on the B server can not get just that cache, as shown in the following figure:

So in order to solve this problem, we have to find a distributed cache, specifically used to store cached data, so that different servers to cache data to be stored in it, take the cached data from it, as shown in the following figure:

This solves the problem mentioned above, in order to improve the system concurrency performance, we generally do the above distributed deployment of the system (cluster deployment mode), so the use of distributed caching for the centralized management of cached data. But MyBatis cannot implement distributed caching, and it needs to be integrated with other distributed caching frameworks, mainly introducing Ehcache. 3.2 Integration Method

As mentioned earlier, the MyBatis provides a cache interface, and if you want to implement your own caching logic, implement cache interface development. The mybatis itself implements one by default, but the implementation of this cache cannot implement the distributed cache, so we have to implement it ourselves. Ehcache distributed caching allows MyBatis to provide a Ehcache implementation class for the cache interface, which is in the MyBatis and ehcache consolidation packages. So first we need to import the consolidation package (point I download).

After the jar package has been imported, the type in cache in Mapper is configured as the implementation type for the cache interface Ehcache. The Ehcache has an implementation class for the cache interface:

We write the fully qualified name of the class to the type attribute, as follows:

OK, Configuration complete, now MyBatis will automatically execute the Ehcache implementation class. You will not use your default level two cache, but use Ehcache to have a cache configuration. Don't 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
            Maxelementsinmemory= "10000"
            eternal= "false"
            timetoidleseconds= "
            timetoliveseconds=
            " maxelementsondisk= "10000000"
            diskexpirythreadintervalseconds= "memorystoreevictionpolicy=" "
            LRU" >
        <persistence strategy= "Localtempswap"/>
    </defaultCache>
</ehcache>

The role of this configuration is similar to hibernate, you can refer to my article Hibernate two cache blog. The next step is to test, or use the above test program, because only changed 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 the user's real-time requirements for query results 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 billing query SQL. The implementation method is as follows: By setting the refresh interval time, automatically clears the cache by the MyBatis every time, according to the data change frequency sets the cache refresh interval flushinterval, for instance set to 30 minutes, 60 minutes, 24 hours, according to the requirement.
MyBatis level two cache for fine-grained data-level cache implementation is not good, such as the following requirements: The product information caching, due to the large number of commodity information query access, but require users to be able to query the latest commodity information, At this point, if you use the MyBatis level two cache, you will not be able to refresh the cached information of the product when a product changes and not refresh the information of other products. Because the level two cache area of the mybaits is divided into mapper units, when a change in the information of a commodity clears all the cached data of the product information. Resolving such problems may require a targeted cache of data at the business layer based on requirements.
  

Related reading: http://blog.csdn.net/column/details/smybatis.html
Learn notes Source download address: Https://github.com/eson15/MyBatis_Study

-– is willing to share and make progress together.
-– my Blog Home: http://blog.csdn.net/eson_15

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.