[英]Hibernate second level cache, one to many
我第一次尝试根据不同的教程使用二级缓存,但它不起作用。 我有课 :
@Entity
@Table(name="TABLE_NAME")
@org.hibernate.annotations.Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Sentence> collection_name;
和我的 hibernate.cfg.xml 文件中的配置
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
我打开了
<property name="show_sql">true</property>
我认为第二个查询不会命中数据库,但确实如此。
我的查询:
List<Foo> result = session.createQuery("select p from Foo p order by size(p.collection_name) desc ").list();
怎么了 ?
如果要缓存HQL查询结果,则必须对查询进行检测:
List<Foo> result = session
.createQuery("select p from Foo p order ... ")
.setCacheable(true)
.list();
另外,您可以告诉Hibernate它应该使用哪个缓存配置(缓存区域):
List<Foo> result = session
.createQuery("select p from Foo p order ... ")
.setCacheable(true)
.setCacheRegion("foo_region")
.list();
当然,全局设置hibernate.cache.use_query_cache
必须设置为true
。
实体类上的@Cache
批注用于通过ID提取单个实体时对其进行缓存:
Foo foo = session.get(Foo.class, fooId);
在 foo.java 和 Sentence.java 中指定 @Cacheable ``@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
同样在@OneToMany 注释之后指定``@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
如果您使用的是 Query 对象:Query q 启用可缓存为 true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.