Mybatis BASICS (8) ----- query cache, mybatis -----

Source: Internet
Author: User
Tags time in milliseconds

Mybatis BASICS (8) ----- query cache, mybatis -----
1. What is query cache?

Mybatis provides query cache to reduce data pressure and improve database performance.

Mybaits provides Level 1 cache and level 2 cache.

 

1.1. The first-level cache is a sqlSession-level cache. When operating the database, you need to construct a sqlSession object. The object has a data structure (HashMap) used to store cached data. The cache regions (HashMap) of different sqlsessions do not affect each other.

1.2. The second-level cache is a mapper-level cache. Multiple sqlsessions operate on the same Mapper SQL statement. Multiple sqlsessions can share the second-level cache, and the second-level cache is cross-sqlSession.

1.3. Why cache?

If there is data in the cache, you do not need to obtain it from the database. This reduces the number of interactions with the data and greatly improves the system performance.

Ii. Level 1 Cache

2.1. How Level 1 cache works

 

A. For the first time, query user information with user id 1. First, check whether the cache contains user information with id 1. If not, query user information from the database.

Obtain the user information and store the user information in the level-1 cache.

B. If sqlSession executes the commit operation (insert, update, delete) and clears the first-level cache in SqlSession, this aims to make the cache store the latest information,

Avoid dirty reading.

C. Initiate the second query of user information with a user id of 1. First, find out whether there is user information with id 1 in the cache. If there is user information in the cache, directly obtain user information from the cache.

Mybatis supports level-1 caching by default. The test is very simple, so no code will be posted here.

2. applications with a level-1 Cache

Formal development. If the project is integrated development of mybatis and spring..., the transaction is controlled in the service.

A service method includes many er method calls.

Service {

// When starting execution, start the transaction and create the SqlSession object

// Call the mapper method findUserById (1) for the first time)

// Call the mapper method findUserById (1) for the second time to retrieve data from the first-level cache

// Method ends and sqlSession is disabled

}

If two service calls are executed to query the same user information, the first-level cache is not taken. Because the session method ends, the sqlSession is closed and the first-level cache is cleared.

Iii. Secondary Cache

3.1 Working Principle of level 2 Cache

  

3.1.1. Enable the secondary cache of mybatis.

3.1.2. sqlSession1: query the user information with the user ID 1. the query data is stored in the second-level cache.

3.1.3. If SqlSession3 executes the SQL statement under the same mapper, execute commit and clear the data in the second-level cache area of The mapper.

3.1.4. sqlSession2: query the user information with the user ID 1 and check whether there is data in the cache. If there is data in the cache, retrieve the data directly from the cache.

 The second-level cache is different from the first-level cache. The second-level cache has a wider range. Multiple sqlsessions can share the second-level cache region of a UserMapper.

UserMapper has a second-level cache area (by namespace), and other mapper also has its own second-level cache area (by namespace ).

The mapper of each namespace has a two-Cache region. If the two mapper namespaces are the same, the two mapper SQL queries and the data will be in the same second-level cache region.

3.2. Enable Level 2 Cache

The second-level cache of mybaits is at the mapper range level. Besides setting the second-level cache in SqlMapConfig. xml, you must enable the second-level cache in the specific mapper. xml file.

Add the following content to the core configuration file SqlMapConfig. xml:

<Setting name = "cacheEnabled" value = "true"/>

 

Description

Allowed value

Default Value

CacheEnabled

Enable or disable global settings for all the caches in this configuration file.

True false

True

A. Enable the secondary cache in sqlMapConfig. xml, the core configuration file of mybatis. In fact, the default value is true, which facilitates code maintenance.

<! -- Global parameter configuration --> <settings> <! -- Enable Level 2 Cache --> <setting name = "cacheEnabled" value = "true"/> </settings>

B. Implement the serialization interface for entity-class users

Public class User implements Serializable {// attribute... // getter and setter ......}

In order to retrieve the cache data and perform deserialization, because the second-level cache data storage media are diverse and different in the memory.

C. Junit test:

// Second-level cache Test @ Test public void testCache2 () throws Exception {SqlSession sqlSession1 = sqlSessionFactory. openSession (); SqlSession sqlSession2 = sqlSessionFactory. openSession (); SqlSession sqlSession3 = sqlSessionFactory. openSession (); // create the proxy object UserMapper userMapper1 = sqlSession1.getMapper (UserMapper. class); // For the first request initiated, query User user1 with id 1 = userMapper1.findUserById (1); System. out. println (user1); // run the close operation here to write the data in sqlsession to the second-level cache region sqlSession1.close (); // use sqlSession3 to execute the commit () operation UserMapper userMapper3 = sqlSession3.getMapper. class); User user = userMapper3.findUserById (1); user. setUsername ("Zhang Mingming"); userMapper3.updateUser (user); // run the submit command to clear sqlSession3.commit (); sqlSession3.close (); UserMapper userMapper2 = callback (UserMapper. class); // For the second request, query the User user2 with id 1 = userMapper2.findUserById (1); System. out. println (user2); sqlSession2.close ();}

3. Disable secondary Cache 

Setting useCache = false in statement disables the second-level cache of the current select statement, that is, each query sends an SQL query. The default value is true, that is, this SQL uses the second-level cache.

<Select id = "findOrderListResultMap" resultMap = "ordersUserMap" useCache = "false">

3. 4. Refresh the cache

In the same namespace of mapper, if there are other insert, update, and delete operations, the cache needs to be refreshed. If no refresh cache is executed, dirty reads will occur.

Set the flushCache = "true" attribute in the statement configuration. By default, if it is true, the cache is refreshed. If it is set to false, the cache is not refreshed. When cache is used, dirty read occurs if you manually modify the query data in the database table.

As follows:

<Insert id = "insertUser" parameterType = "com. mybaits. entity. User" flushCache = "true">

3.5.Mybatis Cache Parameters

LushInterval (refresh interval) can be set to any positive integer, and they represent a reasonable period of time in milliseconds. By default, It is not set, that is, there is no refresh interval, and the cache is refreshed only when the statement is called.

Size can be set to any positive integer. Remember the number of objects you cache and the number of available memory resources in your runtime environment. The default value is 1024.

The readOnly (read-only) attribute can be set to true or false. The read-only cache returns the same instance of the cached object to all callers. Therefore, these objects cannot be modified. This provides an important performance advantage. A readable cache returns a copy of the cached object (serialized ). This is slow but secure, so the default value is false.

Example:

<Cache eviction = "FIFO" flushInterval = "60000" size = "512" readOnly = "true"/>

This more advanced configuration creates a FIFO cache and refreshes every 60 seconds. The number of result objects or 512 references to the list are stored, and the returned objects are considered read-only, therefore, modifying the callers in different threads may cause a conflict. Available recovery policies include LRU by default:

. Second-level cache application scenarios

You can use the mybatis second-level cache technology to reduce the database access volume and increase the access speed for multiple query requests and the real-time requirement on query results. business scenarios include: time-consuming statistical analysis SQL and telephone bill query SQL.

The implementation method is as follows: by setting the refresh interval, mybatis automatically clears the cache at intervals of time, and sets the cache Refresh Interval flushInterval according to the Data Change frequency, for example, set it to 30 minutes, 60 minutes, or 24 hours, depending on your needs.

. Limitations of level-2 Cache

The mybatis second-level cache is not good for fine-grained data-level caches. For example, you need to cache the commodity information because the commodity information query traffic is large, but the user is required to query the latest commodity information each time, in this case, if the second-level cache of mybatis is used, the cache information of the product cannot be refreshed only when the product changes, rather than the information of other products, because the second-level cache area of mybaits is divided by mapper, when a commodity information changes, the cache data of all commodity information is cleared. To solve this problem, you must cache data at the business layer as needed.

Related Article

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.