Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use primary and secondary caches in MyBatis

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you the "primary and secondary cache in MyBatis how to use", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn how to use the primary and secondary cache in MyBatis "this article.

1.1 what is caching

Cache is temporary data in memory. By putting our "frequently queried but infrequent data" in memory, when we query data, we no longer need to read from disk, but only need to query from the cache. The efficiency of query is greatly improved and the performance problem of high concurrency system is solved.

1.2 Why do you need caching

Since we can query data directly from the database, why do we need caching? Through the use of cache, we can reduce the frequency of interaction with the database, reduce system overhead, and thus improve the efficiency of the system.

2. MyBatis cache

MyBatis has built-in a powerful transactional query caching mechanism, which can be easily configured and customized. By default, MyBatis defines two-level cache by default, and in order to improve scalability, we define the cache interface Cache. We can easily implement the Cache interface to customize the second-level cache.

"first-level cache": also known as "local cache", which is enabled by default (SqlSession-level cache); "second-level cache": based on namespace-level cache, which needs to be opened and configured manually; 3. First-level cache

Also known as "local cache", the data queried during the same session with the database is placed in the local cache. When you want to get the same data again, you can get it directly from the cache without having to interact with the database again.

3.1 first-level caching principle

There is an Executor in every SqlSession and another LocalCache in each Executor. When we perform a query operation, MyBatis generates a MapperdStatement based on the currently executed statement, then queries it in LocalCache and returns it directly to the user if it exists (hit). If it does not exist in the cache (missed), it interacts with the database to query the data, writes the result to Local Cache, and returns it to the user.

3.2 how to use first-level caching

First-level cache, that is, SqlSession-level cache, similar to our previous CURD operation.

First add a method to the interface; @ Select ("select * from user where id=# {id}")

User queryUserById (@ Param ("id") int id)

Test @ Test

Public void testQueryUserById () {

SqlSession sqlSession = MybatisUtil.getSqlSession ()

UserDao mapper = sqlSession.getMapper (UserDao.class)

User user1 = mapper.queryUserById (1)

System.out.println (user1)

User user2 = mapper.queryUserById (1)

System.out.println (user2)

System.out.println (user1 = = user2)

SqlSession.close ()

}

Result

As can be seen from the results, since it is during a session (SqlSession level), the SQL statement at this time is only queried once, and when the same result is obtained the second time, the result can be taken directly from the cache, which explains why user1 and user2 point to the same object.

3.3 invalidation of first-level cache

First-level caching is always on by default, and we can't turn it off. But sometimes the first-level cache will fail, which may be caused by the following reasons

"caching independently in each SqlSession"

When we use different SqlSession, we need to make as many query requests to the database as there are SqlSession.

@ Test

Public void testQueryUserById () {

SqlSession sqlSession1 = MybatisUtil.getSqlSession ()

UserDao mapper1 = sqlSession1.getMapper (UserDao.class)

SqlSession sqlSession2 = MybatisUtil.getSqlSession ()

UserDao mapper2 = sqlSession2.getMapper (UserDao.class)

User user1 = mapper1.queryUserById (1)

System.out.println (user1)

User user2 = mapper2.queryUserById (1)

System.out.println (user2)

System.out.println (user1 = = user2)

SqlSession1.close ()

SqlSession2.close ()

}

"when the data does not exist in the current cache"

When the same SqlSession is located, but the query conditions are different, it will also cause cache invalidation.

@ Test

Public void testQueryUserById1 () {

SqlSession sqlSession = MybatisUtil.getSqlSession ()

UserDao mapper = sqlSession.getMapper (UserDao.class)

User user = mapper.queryUserById (1)

System.out.println (user)

User user2 = mapper.queryUserById (2)

System.out.println (user2)

System.out.println (user = = user2)

SqlSession.close ()

}

"other CURD operations affect the current data"

If other operations such as additions, deletions and modifications are carried out between two queries in the same SqlSession, the SQL statement will be re-executed when the second query is carried out, resulting in cache invalidation

@ Test

Public void testQueryUserById () {

SqlSession sqlSession = MybatisUtil.getSqlSession ()

UserDao mapper = sqlSession.getMapper (UserDao.class)

User user = mapper.queryUserById (1)

System.out.println (user)

Mapper.updateUser (new User (2, Xiaoyu, 8349823))

User user2 = mapper.queryUserById (1)

System.out.println (user2)

System.out.println (user = = user2)

SqlSession.close ()

}

"Manual cleanup"

When the SqlSession is the same, if we manually clear the cache, it will also lead to cache invalidation.

@ Test

Public void testQueryUserById1 () {

SqlSession sqlSession = MybatisUtil.getSqlSession ()

UserDao mapper = sqlSession.getMapper (UserDao.class)

User user = mapper.queryUserById (1)

System.out.println (user)

/ / manually clear the cache

SqlSession.clearCache ()

User user2 = mapper.queryUserById (1)

System.out.println (user2)

System.out.println (user = = user2)

SqlSession.close ()

}

4. Second-level cache

Also known as "global cache", namespace-based cache, one namespace corresponds to a secondary cache.

4.1 the principle of two-tier cache

The maximum sharing scope of the first-level cache is within a SqlSession. If you want to share the cache among multiple SqlSession, you need to use the second-level cache. Once the second-level cache is enabled, there will be multiple CachingExecutor to decorate the Executor. Before entering the query process of the first-level cache, perform the second-level cache query in CachingExecutor, as shown in the figure above. At this point, the query process of the data is:

Second-level cache-> first-level cache-> database

❞4.2 how to use secondary caching

To use secondary caching, you usually need to take the following steps:

First, turn on the secondary cache in the MyBatis configuration file (usually mybatis-config.xml)

Then configure the secondary cache in the corresponding xxxMapper.xml

After configuration, the select statements in the xxxMapper.xml file will be cached, while insert, update, and delete will flush the cache. In addition, you can set custom property values to modify the default property.

Property describes the eviction purge policy flushInterval refresh interval in the number of mssize references. Default is 1024readOnly. Default is false.

There are four main cleaning strategies:

The cleanup policy states that LRU is "least recently used": remove objects that have not been used for the longest time FIFO "first-in, first-out": remove SOFT "soft references" in the order in which they enter the cache: remove object WEAK "weak references" based on garbage collector state and soft reference rules: more actively test @ Test based on garbage collector state and if reference rules remove objects

Public void testGetUserByPassword () {

SqlSession sqlSession = MybatisUtils.getSqlSession ()

SqlSession sqlSession2 = MybatisUtils.getSqlSession ()

UserDao mapper = sqlSession.getMapper (UserDao.class)

UserDao mapper2 = sqlSession.getMapper (UserDao.class)

User user = mapper.getUserByPassword ("1234567")

System.out.println (user)

User user2 = mapper2.getUserByPassword ("1234567")

System.out.println (user2)

System.out.println (user==user2)

SqlSession.close ()

SqlSession2.close ()

}

Result

As can be seen from the results, the secondary cache is already in effect at this time. If it does not take effect, it will be consistent with the result in the first-level cache, and the two points to different objects, but in this case, the two references point to the same object, indicating that the secondary cache is successful.

These are all the contents of the article "how to use first-and second-tier caches in MyBatis". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report