您的位置:首页 > 其它

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

2016-08-26 13:59 489 查看

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>


之后再配置需要二级缓存的类.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: