MyBatis learning summary (ten): MyBatis's primary cache and secondary cache

1. Introduction to caching

(1) What is cache?

The original meaning refers to a type of RAM that has a faster access speed than general random access memory. Usually it does not use DRAM technology like the main memory of the system, but uses expensive but faster SRAM technology. The so-called cache in programming is to store
the objects (temporary data) frequently called by the program or the system in the memory, so that they can be called quickly when in use, without the need to create new repeated instances.

(2) What is the meaning of caching?

Caching is used to reduce the number of interactions with the database, which can reduce system overhead and improve execution efficiency.

(3) Data suitable for caching

Applicable to cached data: frequently queried and infrequently changed, and the correctness of the data has little effect on the final result.

Not applicable to cached data: data that changes frequently, the correctness of the data has a great influence on the final result.

2. Level 1 cache

The first level cache of MyBatis is actually a sqlsession level, which means that sqlsession can only access the data of its own level one cache. The first-level cache query exists in each instance object of the sqlsession class. When a certain data is queried for the first time, the instance object of the sqlsession class will store the data in the first-level cache. In this way, before receiving a request to change the data, the data we query is obtained from the cache instead of the data from the database, which greatly reduces frequent database queries and reduces efficiency. When we query again, whether it exists in the SqlSession, if any, use it directly. When the SqlSession object disappears, the level one cache information in MyBatis will also disappear.

image

Circumstances that trigger the emptying of the first-level cache:

  • clearCache(): Clear the cache
  • Data changes: The first level cache is a cache within the scope of SqlSession. When the modify, delete, add, commit(), close() and other methods of SqlSession are called, the first level cache will be cleared.

The scope of the first-level cache is SESSION and STATEMENT. The default is SESSION. If you do not want to use the first-level cache, you can specify the scope of the first-level cache as STATEMENT, so that the first-level cache will be cached every time a statement in the Mapper is executed. Clear.
If you need to change the scope of the first level cache, you can specify it under localCacheScope in the Mybatis configuration file.
as follows:

<setting name="localCacheScope" value="STATEMENT"/>

3. Level 2 cache

The second-level cache refers to the mapper under the same namespace. In the second-level cache, there is also a map structure. This area is the first-level cache area. The key in the first level cache is a unique value composed of information such as SQL statements, conditions, and statements. The value in the first level cache is the result object of the query.

image

Steps for usage:

(1) Open the secondary cache in SqlMapperConfig.xml.

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

(2) Open the second level cache in the mapper mapping file.

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

Property description:

parameter name Attributes
eviction Retraction strategy
flushInterval Refresh interval
size Number of references
readOnly Read only

About the various parameter attributes of eviction:

parameter name Attributes
eviction="LRU" Least recently used: Remove objects that have not been used for the longest time. (default)
eviction="FIFO" First in, first out: Remove objects in the order they enter the cache.
eviction="SOFT" Soft references: Remove objects based on garbage collector status and soft reference rules.
eviction="WEAK" Weak references: More aggressively remove objects based on garbage collector status and weak reference rules.

(3) Let the current operation support the secondary cache-configuration in the select tag (useCache="true")

Example:

(1) Open the secondary cache in SqlMapperConfig.xml.

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

(2) Open the second level cache in the userMapper mapping file.

 <cache></cache>

(3) Let the current operation support the secondary cache

<!-- 根据id查询用户   -->
    <select id="findById" parameterType="Integer" resultType="com.day1.entity.User" useCache="true">
        select * from t_user where id = #{id}
    </select>

After testing, the execution results are as follows: 

to sum up:

The first level cache of mybatis is a SqlSession level cache, and the first level cache caches objects. When the SqlSession submits, closes, and other operations to update the database occur, the first level cache will be emptied.

The second-level cache is a SqlSessionFactory-level cache. SqlSessions generated by the same SqlSessionFactory share a second-level cache. Data is stored in the second-level cache. When the second-level cache is hit, the object is returned by the stored data. When querying data, the query process is level two cache> level one cache> database . 

4. Summary of errors

错误信息:Cause: org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: java.io.NotSerializableException: com.day1.entity.User

Reason: The entity class User does not implement the serialization interface. The secondary cache in MyBatia stores data, which needs to be deserialized to create objects.

Solution : Let User implement the serialization interface.

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113842001