Hibernate 是一种流行的 Java 开源对象关系映射解决方案。 为了提高性能,Hibernate 还提供了缓存的特性。 Hibernate 提供了两种缓存,一级缓存和二级缓存。
一级缓存是内置的并用作默认值,但它的使用受到限制,不可访问,并且只是一个进程内缓存。 二级缓存提供了可插拔的架构,这意味着第三方缓存可以用作 Hibernate 的二级缓存。
NCache 实现了 Hibernate 二级缓存提供程序,从而减轻了数据库执行负担并最大限度地减少了 SQL 流量。这允许直接配置而无需更改代码,使您的应用程序能够立即访问 NCache强大的分布式缓存功能套件。
配置 NCache 因为 Hibernate 的二级缓存非常简单。 无需更改实际代码。 只需要编辑配置文件。
现在添加 NCache 作为 Hibernate 的二级缓存,必须按以下方式编辑 hibernate.cfg.xml:
以下是在 中所做更改的示例 休眠文件.cfg.xml 文件:
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">JCacheRegionFactory</property>
...
</session-factory>
</hibernate-configuration>
兼容性说明: 此配置与 Hibernate 版本 3.6 至 6.x 兼容,并支持任何使用 JCache (JSR-107) 标准的 Java 环境。
Hibernate 利用 缓存区域 用于存储对象。 NCache 允许配置具有不同属性的这些缓存区域。 这 NCacheHibernate.xml 文件用于此目的。 该文件包含所有区域的配置设置和选项以及使用的相关配置 NCache.
以下是一个示例 NCache配置区域的 Hibernate.xml 配置文件:
<configuration>
<application-config application-id="myapp" enable-cache-exception="true" default-region-name="DefaultRegion" key-case-sensitivity="false">
<cache-regions>
<region name="hibernator.BLL.Customer:Customer" cache-name="myPartitionedcache" priority="BelowNormal" expiration-type="Absolute" expiration-period="8"/>
<region name="DefaultRegion" cache-name="myPartitionedcache" priority="default" expiration-type="none" expiration-period="0" />
</cache-regions>
...
</application-config>
</configuration>
NCache 是一个功能全面、高效且有效的分布式缓存,适用于 .NET Framework、.NET Core 和 Java。它提供了一系列丰富的特性和功能。其中一项特性是通过数据库同步实现的。 SQL 依赖. 这是缓存检查数据库是否有任何更改,并重新加载或删除发现过时或冗余的项目的地方。
NCache 利用原生数据库通知(例如 SQL 依赖项或 Oracle 依赖项)来同步 Hibernate L2 缓存。这确保了如果第三方应用程序修改数据库, NCache 自动使受影响的 Hibernate 实体失效或重新加载。要启用此功能,请对以下内容进行更改: NCache休眠.xml 文件:
<configuration>
<application-config application-id="myapp" enable-cache-exception="true" default-region-name="DefaultRegion" key-case-sensitivity="false">
...
<database-dependencies>
<dependency entity-name="hibernator.BLL.Customer" type="oracle" sql-statement="select ContactName from Customer where CustomerID ='?'" cache-key-format="hibernator.BLL.Customer#[pk]" connection-string="Your Connection String"/>
</database-dependencies>
</application-config>
</configuration>
Hibernate 提供了一个特性 查询缓存. 这里查询的结果被缓存在二级缓存中。 NCache 允许您使用此功能缓存此类查询。 此功能可以通过编辑启用 休眠文件.cfg.xml 文件方式如下:
<hibernate-configuration>
<session-factory>
...
<property name="hibernate.cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
默认情况下,启用查询缓存不会缓存每个查询。 相反,需要缓存的查询将在代码中设置为可缓存。 要设置查询可缓存,请在创建查询时调用查询的 setCacheable(true) 函数。 下面的代码是一个显示可缓存查询的示例:
List customerEnumerator = session.createQuery("from Customer c").setCacheable(true).list();
以下是主要原因 NCache 是在应用程序在多服务器环境中运行时用作 Hibernate 的二级缓存的合适选项。
hibernate.cache.use_second_level_cache 在 hibernate.cfg.xml 文件中设置属性并进行设置 hibernate.cache.region.factory_class 至 JCacheRegionFactory此设置无需对您的应用程序代码进行任何更改。hibernate.cache.use_query_cache 财产 true 在配置文件中,并在 Java 代码中使用以下方式将特定查询标记为可缓存: setCacheable(true) 方法。