Hibernate cache

1. Don't use cache

<1> Use the same session to execute the query The second query to the same object just returns the first volume of query results instead of re-using the SQL statement to query the database

2. Level 1 cache (Session cache)

  • introduce
  1. Querying an entity from the database through the session will store the entity in the memory. The next time the same entity is queried, it will not be obtained from the database, but from the memory.
  2. The life cycle of the first level cache is the same as that of the Session
  • The API
    level 1 cache cannot be cancelled, and two methods are used to manage it
    <1> evict(): used to clear an object from the Session level 1 cache
    <2> clear(): used to clear all objects in the level 1 cache clear
  • Question
    <1> query.list() will not use the cache
    <2> query.iterate() The execution process is to query the ID of the object, and then search for the cache according to the ID. If you don’t find yourself, go to the database to find it.

    3. L2 cache

  • Introduction
    Each session shares the cache, which is not enabled by default
  • Configuration steps
    <1>JAR import
    <2>SRC -> ehcache.xml
    <3>hibernate.cfg.cml Configure the second-level cache entry (specify the external implementation class of the second-level cache)
    <4>In the configuration file of the corresponding entity class Enable L2 cache
  • <4>
    事务模式 只读
    <cache usage="read-only" include="all或者non-lazy" region="任意名"
    non-lazy 当本表关联其他表的属性时 不设置那个属性
    region对应的value可以在ehcache.xml中对应标签 设置他的缓存策略(最大缓存数量,缓存对象永久)

4. 二级缓存 & 一级缓存

  • 试用情况
    <1>很少被修改的数据

<2>不是很重要的数据,允许出现偶尔并发的数据

属性 | 一级缓存 | 二级缓存

---|--- | ---

缓存的范围|事务范围 每个事务都拥有单独一级缓存|应用范围,当前应用内所有事务共享

并发访问策略|不会出现并发问题|必须提供适当的并发访问策略

数据过期策略|没有数据过期策略|缓存对象的最大数目、最长时间、最长空闲时间等

缓存的软件实现|框架包含|第三方提供、可插拔集成

物理介质|内存|内存和硬盘

启用方式|默认启用、不可关闭|默认不启用、选择性开启

5. 缓存算法

LRU Least Recently Used
LFU Least Frequently Used
FIFO First In First Out

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325375333&siteId=291194637