我们有代表查找值(州、国家代码等)的JPA实体。经常调用以获取
List
使用
org.springframework.cache.annotation.Cacheable
注释(如适用)。
我们还有与这些查找实体有关系的实体,定义如下:
@Entity
@Table(name = "Address")
public class AddressEntity {
// ...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STATE_CD", referencedColumnName = "CD")
@NotNull
private StateEntity state;
// ...
}
当我们加载其中一个实体,然后调用相关查找的getter时,Hibernate会再次点击数据库来加载该值。当我们有了地址并进行
getState
在该地址上,我们访问本地缓存以获取该信息。我们如何使用Hibernate/JPA实现这一点?
// Get address:
Address address = addressRepo.findOne(addressId);
// Get the state - this causes an additional query to hit the database:
State state = address.getState();