java - hibernate 缓存策略

标签 java hibernate orm ehcache second-level-cache

我如何决定使用哪个 CacheConcurrencyStrategy

  • NonstrictReadWriteCache,
  • ReadOnlyCache,
  • ReadWriteCache,
  • TransactionalCache.

我读过 https://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/CacheConcurrencyStrategy.html ,但解释的不够详细。

最佳答案

Hibernate documentation在定义它们方面做得很好:

19.2.2. Strategy: read only

If your application needs to read, but not modify, instances of a persistent class, a read-only cache can be used. This is the simplest and optimal performing strategy. It is even safe for use in a cluster.

19.2.3. Strategy: read/write

If the application needs to update data, a read-write cache might be appropriate. This cache strategy should never be used if serializable transaction isolation level is required. If the cache is used in a JTA environment, you must specify the property hibernate.transaction.manager_lookup_class and naming a strategy for obtaining the JTA TransactionManager. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called. If you want to use this strategy in a cluster, you should ensure that the underlying cache implementation supports locking. The built-in cache providers do not support locking.

19.2.4. Strategy: nonstrict read/write

If the application only occasionally needs to update data (i.e. if it is extremely unlikely that two transactions would try to update the same item simultaneously), and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate. If the cache is used in a JTA environment, you must specify hibernate.transaction.manager_lookup_class. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called.

19.2.5. Strategy: transactional

The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache can only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.

换句话说:

  • 只读:适用于经常读取但从未更新的数据(例如国家/地区等引用数据)。很简单。它具有所有(显然)最好的性能。

  • 读/写:如果您的数据需要更新,这是理想的选择。但它不提供 SERIALIZABLE隔离级别,phantom reads可能会发生(您可能会在事务结束时看到开始时不存在的东西)。它比只读有更多的开销。

  • 非严格读/写: 或者,如果两个单独的事务线程不太可能更新同一个对象,您可以使用非严格读/写策略。它的开销比读写少。这对于很少更新的数据很有用。

  • 事务性:如果您需要完全事务性缓存。仅适用于 JTA 环境。

因此,选择正确的策略取决于数据是否更新、更新频率和所需的隔离级别。如果您不知道如何为要放入缓存的数据回答这些问题,可以向 DBA 寻求帮助。

关于java - hibernate 缓存策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1837651/

相关文章:

hibernate - JPA 与 Hibernate - 合并性能问题

.net - 特性 - NHibernate 与编写自定义对象关系映射器

nhibernate - 流利的NHibernate HasManyToMany()映射

python - 使用 Flask 和 SQLAlchemy 从不同的连接表中选择属性

java - JAXB - 如果设置了另一个可选属性,是否可以使可选属性成为必需属性?

java - 如何在二维数组上实现线性扫描?

java - 集合元素(多对多)表别名不能为空

java - 如何根据从 jtextfield 和组合框接收的值将数据行添加到 Jtable

java - 将 TreeSet 转换为 ArrayList?

java - 使用 Hibernate 的 Spring Boot 在使用 H2 数据库启动时生成丢弃约束错误