Hibernate 一级缓存(First-level cache)和二级缓存(second-level cache) 介绍

Hibernate 一级缓存(First-level cache)和二级缓存(second-level cache) 介绍

分别是什么?

First-level cache:
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

Second-level cache:
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

Quoted from: http://www.javabeat.net/articles/37-introduction-to-hibernate-caching-1.html

一级缓存:
一级缓存,缓存的是session对象。Hibernate默认采用这种缓存方式。一般来说,session处理一个事务之后才可以处理另外一个事务,不会处理一个事务多次。这种方式就会减少事务里Sql query的次数。因为我们缓存了session的object,只用在transaction的提交时整体commit一次,而不是在每次修改后都update.

二级缓存:
二级缓存, 缓存的是Session Factory产生的对象。当在事务中的时候,由于缓存的是整个session factory level的对象,所以这些对象不只是对单独的一个用户有效,而是对整个应用都有效的。由于这些对象已经被加载到内存中,从查询返回的对象之后,以后的获取就不再需要数据库的事务了。第二级缓存就是这么工作的。这里我们也使用到了查询缓存,在以后的篇章我们将讨论。


二级缓存配置:

配置sessionFactory的时候配置二级缓存,常用的是ecache。需要类似于下面的配置(根据版本不同发生变化):

<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

之后再配置需要二级缓存的类.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值