Cache of MyBatis

Source: Internet
Author: User

MyBatis and Hibernate have the same level of cache and level two cache .

1. First- level cache: MyBatis The scope of a cache is the same sqlsession.

Write an example of a query User:

<!--user query-<select id= "Finduserbyid" parametertype= "int" resulttype= "user" > select * from Users where UserId = #{user_id} </select>
Test level cache @testpublic void TestCache1 () throws Exception {//get sqlsessionsqlsession sqlsession = Sqlsessionfactory.opensession (); Ordermapper ordermapper = Sqlsession.getmapper (Ordermapper.class);//query user user for the first time = new User (); User.setuserid (100108); System.out.println ("-----------------first query, get--------------------from the database"); User GetUser = Ordermapper.finduserbyid (User.getuserid ()); System.out.println (GetUser); System.out.println ("-----------------second query, get--------------------from cache");//execute the same query again user GetUser2 = Ordermapper.finduserbyid (User.getuserid ()); System.out.println (GETUSER2);}

Execution Result:

As you can see from the results: The first query, SQL was executed in the database. And the second time did not get results by querying the database,

Instead, it gets from the cache. So what is the mechanism of caching?

sqlsession caching mechanism: When executing a SQL, MyBatis will first go to the cache (Perpetualcache) to query the key

Result set, A. If there is no query to the database, the query succeeds, the result is written to the cache; B. If it does, it is directly from the cache

Remove the result set returned.

MyBatis Internal storage cache uses a hashmap<cachekey, object>, key is Hashcode + sqlid + SQL statement

Format, value is the Java object that the query is generated by mapping.

Question: If the User's information is updated before the second query, will the second query take the data out of the cache or query again?

The result is obvious that the cache will be emptied when the update or delete operation is done. So it will be queried again.

2. level Two cache: the query cache, which is scoped to a mapper namespace, that is, the query SQL in the same namespace

Data can be obtained from the cache. A secondary cache can be cross-sqlsession.

A. Turn on level Two cache: add to Sqlmapconfig.xml <settings>...</settings>

<!--turn on level two cache--><setting name= "cacheenabled" value= "true"/>
Property name Describe Allowed values Default value
Cacheenabled Global on/Off settings for all caches under this profile True/false True

B. Add <cache/> In the Mapper.xml file to turn on caching

<mapper namespace= "Mybatis_b.mapper.OrderMapper" > <!--turn on this mapper level two cache--<cache/></mapper>

C. Java calls, where two sqlsession are used to implement a two-level cache across sqlsession

//Test Level Two cache @testpublic void testcache2 ()  throws exception {//Get sqlsessionsqlsession sqlsession =  Sqlsessionfactory.opensession (); Ordermapper ordermapper = sqlsession.getmapper ( Ordermapper.class); Sqlsession sqlsession2 = sqlsessionfactory.opensession ();         ordermapper ordermapper2 = sqlsession2.getmapper (OrderMapper.class);//query user for the first time  user = new user (); User.setuserid (100108); System.out.println ("-----------------first query, get--------------------from the database"); User getuser = ordermapper.finduserbyid (User.getuserid ()); System.out.println (GetUser);//close session1sqlsession.close (); System.out.println ("-----------------second query, get--------------------from cache");//execute the same query again user getuser2 =  ordermapper2.finduserbyid (User.getuserid ()); System.out.println (GetUser2); Sqlsession2.close ();} 

Where the User class implements the serialization interface. After execution, it is found that the second time is actually getting data from the cache, and the results are not posted.

Question: If you update a data after the first query is finished, will the second time fetch the data from the cache? Is the result up to date?

Result: The second time is still taken from the cache and is up-to-date. Because: in the same namespace of mapper, if there is

Other insert, UPDATE, delete operation data need to flush the cache, and dirty reads will occur if not performed. and mapper

SQL has the flushcache= "true" property, which defaults to true to flush the mapper level cache.

3. Other parameters of the Cache:

Flushinterval: The refresh interval, which can be set to any positive integer, represents a reasonable period of time, in milliseconds. The default is

Not set, that is, there is no refresh interval, and the cache is flushed only when the statement is invoked.

Size: The number of references, which can be set to any positive integer, to remember the objects you cache and the available memory resources of the running environment, the default value is 1024

ReadOnly: Read-only property. A read-only cache returns the same instance of the cached object to all callers. Therefore, these objects cannot be modified.

This provides a very important performance advantage. A read-write cache returns a copy of the cached object (by serialization). It's going to be a little slower

, but is safe, so the default is false.

<cache eviction= "FIFO" flushinterval= "60000" size= "Up" readonly= "true"/>

The above cache configuration creates a FIFO cache and refreshes every 60s, storing 512 references to the resulting object or list, and returns the

Objects are considered read-only, so modifying them between callers in different threads can cause conflicts.

The available recycling policies are:

A. LRU-least recently used: remove objects that are not used for the longest time

B. FIFO-First-out: Removes them by the order in which the objects enter the cache.

C. SOFT-Soft Reference: Removes objects based on the garbage collector state and soft reference rules.

D. WEAK-Weak references: More aggressively remove objects based on garbage collector state and soft reference rules.

4. The MyBatis is integrated with the cache framework Eacache and uses the Eacache framework to manage cached data.

A. Introducing cached dependency packages requires Mybatis-ehcache-1.0.3.jar Ehcache-core-2.6.8.jar and Slf4j-api-1.6.1.jar

B. Modify the cache configuration of the Mapper:

<!--The following two <cache> label two select one, the first one can output the log, the second does not output the log--><cache type= "Org.mybatis.caches.ehcache.LoggingEhcache "/><cache type=" Org.mybatis.caches.ehcache.EhcacheCache "/>

Need to be explained ...

Cache of MyBatis

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.