Mybatis system cache buffer 1 ---- Introduction and simple configuration

 

mybatis Cache

  System cache: a common cache and secondary cache

Cache

  SqlSession cache is a level cache, the database needs to be built in operation SqlSession object in the object has a data structure for storing cached data. Cache data between different regions are mutually SqlSession not affected. That is only a role in SqlSession object, between different cache data can not be read are mutually SqlSession.

   A cache works

  

 

 

   Oral presentation:

  When a user initiates a request A query a record, SqlSession existing cache data reads, if there is to read, if it does not exist to get data from the database.

  SqlSession when the commit operation will clear the cache. This is done to avoid dirty reads.

  

  Note: If you do not empty the cache commit an error occurs. For example: A user query when an item as well as 10 and 10 cached in a cache of goods, after being bought by 10 customers, the data is delete away, but this product is the next query from the cache Obtain. Dirty data will appear .

  spring in the integration of mybatis

  After the spring will be placed in the transaction management Service, for each service in SqlSession it is different, which is created automatically injected into the Service SqlSession in each query by mybatis-spring to be in org.spring.mapper.MapperScannerConfigurer Close SqlSession, data will be cleared after closing, so after spring integration if there is no transaction support, L1 cache is meaningless.

 

  Secondary cache

    Secondary cache works

  

 

 

     Oral presentation:

    A secondary cache mapper level cache, a plurality of the same to operate sql'Session mapper sql statement, with a plurality of SqlSession shared secondary cache, the secondary cache across the SqlSession.

   每一个mapper都有一个二级缓存区域(按照namespace区分),每一个namespace的mapper都有二级缓存区域,两个mapper的namespace相同,这两个mapper执行的Sql查询数据存储在同一个二级缓存区域。

    

   开启二级缓存

    1.打开总开关:

    在mybatis的xml文件中加入:

    <settings>

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

    <settings/>

    2.在需要开启二级缓存的mapper.xml文件中引入<cache />

    3.让使用二级缓存的POJO类实现Serializable(序列化)接口

    注:springboot中默认开启了全局二级缓存,如果使用二级缓存需要在mapper上注明。@CacheNamespace

 

    总结:

    好处:对于查询多,commit操作少的。用户对查询条件实时性数据要求不高,采用二级缓存可以降低数据库访问量,提高数据库访问性能。

    弊端:二级缓存是建立在一个namespace下的,如果是多个namespace那么数据可能是错误的。

      

     举例说明:

    部门和部门员工,部门存储在部门的二级缓存下,部门员工存储在部门员工的二级缓存下。如果有人对部门信息进行修改,那么影响的就只有部门的二级缓存,如果在进行查询时,部门员工信息时从部门员工的二级缓存中获取的。这时候的数据是已经过时的。

 

    使用二级缓存的问题:

    对该表的操作都是同一个namespace下,其他namespace如果有操作就会发生脏读。

    对关联表的操作,关联表的所有表的操作都必须在同一个namespace下操作。

Guess you like

Origin www.cnblogs.com/shar-wang/p/11614173.html