[英]Hibernate Second Level Cache - Previously Cached Entities Still being Fetched from DB
My application is using Hibernate and Hazelcast for the level 2 cache.我的应用程序使用 Hibernate 和 Hazelcast 作为 2 级缓存。 My setup has two Entities: Country and Address, whereby an Address has a field of type Country.
我的设置有两个实体:国家和地址,其中地址具有国家类型的字段。
Country is annotated with @Cache and I can see it is present in the level 2 cache after it has been initially fetched from the DB using findById(). Country 使用 @Cache 进行注释,我可以看到它在最初使用 findById() 从数据库中获取后存在于 2 级缓存中。
When I fetch the Address entity which has a @ManyToOne link back to a Country (the one in the level 2 cache) - the level 2 cache is not hit to fetch the previously cached Country, why is this?当我将具有@ManyToOne 链接的地址实体返回到某个国家/地区(二级缓存中的那个)时 - 二级缓存未命中以获取先前缓存的国家/地区,这是为什么呢?
Country Entity国家实体
@Entity(name = "country")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country implements Serializable {
private int countryId;
private String name;
@Id
@Column(name = "country_id")
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Address Entity地址实体
@Entity(name = "address")
public class Address {
private int addressId;
private Country country;
@Id
@Column(name = "address_id")
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "country_id")
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
You have to get one more reference parameter in Country Entity of Address Entity您必须在地址实体的国家实体中再获取一个参考参数
like this像这样
private Address address;
//getter and setter
When I fetch the Address entity which has a @ManyToOne link back to a Country (the one in the level 2 cache) - the level 2 cache is not hit to fetch the previously cached Country, why is this?
当我将具有@ManyToOne 链接的地址实体返回到某个国家/地区(二级缓存中的那个)时 - 二级缓存未命中以获取先前缓存的国家/地区,这是为什么呢?
This depends on a few things.这取决于几件事。
Address
?Address
? If you don't use EntityManager#find
, you will have to configure the query cache hint: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#caching-query (for Spring Data, you need to annotate the method with @QueryHint
EntityManager#find
, you will have to configure the query cache hint: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#caching-query (for Spring数据,需要用@QueryHint
注解方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.