This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

  • Level 1 cache refers to sqlSession. In SQLSession, there is a data area, which is a map structure. This area is called level 1 cache area.

    • A key in a level 1 cache is a unique value consisting of SQL statements, conditions, statements, and other information.
    • The value in the level 1 cache is the queried result object.
  • Level 2 cache refers to the mapper of the same namespace

    • Level 2 cache also has a map structure. The exact structure is the same as the level 1 cache, with the same structure for keys and values.
    • But the life cycle is longer than that of a level 1 cache.

Level 1 caching is used by default. Level 2 cache needs to be manually enabled.

Level 1 Cache (SQLSession cache)

The first query is checked in the cache, and if not, the database is checked and added to the cache. But if there’s an add, delete or change operation and it’s committed, it’s going to clear the level 1 cache.

The level 1 cache contains a hashmap: CacheKey = ‘localCache’; CacheKey = ‘Statement Id, Offset, Limmit, Sql, Params’; Use this object as the cache map key.

The level 1 cache has two levels: SESSION and STATEMENT. By default, the SESSION cache is for the current SESSION. The cache of the two sessions does not affect each other.

There is a problem

  • Cache data of dirty read multiple SQLSessions is inconsistent. Procedure

Level 2 Cache (Mapper cache)

Each mapper cache area. Also add, delete and change will clear the cache. After level-2 Cache is enabled, all operation statements in a namespace affect the same Cache and are shared by multiple SQLSessions.

When caching is enabled, the data query execution process is level 2 cache -> Level 1 cache -> database. First go to level 2 cache, then go to level 1 cache.

configuration

  • In the mapper file<cached/>To enable level 2 caching.
  • <setting name="cacheEnabled" value="true"/>

There is a problem

When the SQL statement is a multi-table query, I change the contents of another namespce table, and that namespce table is not aware of it. That namespace is dirty data.

conclusion

Mybatis caching mechanism should be completely disabled.

  • Mybatis itself is a persistence layer framework, it is not a dedicated caching framework, so it does not implement caching well enough to support distribution.

  • For example, Ehcache is a distributed caching framework. The ehCache package is needed for distributed caching. We can actually implement caching at our code level. If you want to implement your own Cache, just implement the Cache interface, and then configure the Cache in Mapper to use your own class.