最简单的缓存:

一、获取单个缓存数据:(get、load)

配置步骤:
1、首先导入你要使用的缓存包的依赖包(以 EhCache 为例)
2、添加EhCache.xml 配置文件(不用修改赋值到src目录就能用)
3、在 hibernate.cfg.xml 中开启缓存并配置 缓存启动类
4、指定你要缓存的实体类。

<!-- 使用二级缓存,默认是未打开的。 -->
        <!-- 指定要使用的缓存的提供商,这也就打开了二级缓存 
        <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
        -->
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
        <!-- 指定要使用二级缓存的实体类 -->
        <!-- usage="read-write/read-only" -->
        <class-cache usage="read-write" class="cn.itcast.l_second_cache.Employee"/>
        <class-cache usage="read-write" class="cn.itcast.l_second_cache.Department"/>
        <collection-cache usage="read-write" collection="cn.itcast.l_second_cache.Department.employees"/>

代码中:

//下面的在多个事务中都只会执行一次sql查询,以后都从缓存取。(仅限于 get 和load 方法)
//get()和Load() 使用缓存时是根据 id 来获取缓存对象的。不管是一级缓存,还是二级缓存,都是如此。
Department employee = (Department) session.get(Department.class, 5); // 获取
Set<Employee> employees = employee.getEmployees();
for(Employee e:employees){
    System.out.println(e.toString());
}

二、获取缓存列表( iterate、setCacheable(true).list())

方法一:
通过iterate()方法可以获取数据或者缓存,该方式对每一条数据淡出发出一条sql语句,
特点:在没有缓存数据时,如果有一万条数据,就会查询一万次,并缓存,效率很低。再次使用时就会很快。

Iterator<Employee> iterator = session.createQuery("FROM Employee e WHERE e.id<8").iterate();
        while (iterator.hasNext()) {
            Employee e = iterator.next();
            System.out.println(e);
        }

第二中方式:
以sql语句为key来缓存取数据。
在项目中某些sql语句如果不变的情况下,使用起来很方便。
使用方式:
1、需要在hibernate.cfg.xml 开启缓存查询:

<!-- 开启使用查询缓存 用于list()查询-->
<property name="cache.use_query_cache">true</property>

2、代码中需要 setCacheable(true)

//以sql语句为key去二级缓存中查询是否该语句执行过sql查询,
如果有就获取数据,否者就去数据库获取数据,并缓存到二级缓存中。
session.createQuery("sql语句").setCacheable(true).list();
//在另一个事务中第二次调用同一条sql语句时,就会获取到上面放到缓存中的数据了。
//注意两次sql语句必须相同,一个字符都不能修改。
session.createQuery("sql语句").setCacheable(true).list();

三、缓存被修改后的策略:

如果某个表被执行了 delete 或者 update 语句后,
那么该表对应的所有缓存将会被清除。