afaik实体仅通过二级缓存中的主键进行索引,因此查询相关实体将不会使用它:
@Entity
public class Employee {
@Id
@Column(name="EMP_ID")
private long id;
...
@OneToMany(mappedBy="owner")
private List<Phone> phones;
...
}
@Entity
public class Phone {
@Id
private long id;
...
@ManyToOne
@JoinColumn(name="OWNER_ID")
private Employee owner;
...
}
EntityManager em;
// uses 2nd level cache
Employee employee = em.find(Employee.class, 1);
// doesn't use 2nd level cache. Even if 2nd level cache actually
// contains all referenced phones, there will be a DB call.
employee.getPhones();
访问电话并利用二级缓存时,是否可以避免数据库调用?是否有支持自定义索引的缓存实现?
我当前正在将Wildfly 14与hibernate / infinispan一起使用。
访问电话至少会利用查询缓存还是仅使用em.createQuery(...)
?
答案 0 :(得分:0)
我终于找到了解决方案。 Hibernate中有一个集合缓存,必须通过用org.hibernate.annotations.Cache
注释集合来显式启用它。
@Entity
@Cacheable(true)
public class Employee {
@Id
@Column(name="EMP_ID")
private long id;
...
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@OneToMany(mappedBy="owner")
private List<Phone> phones;
...
}
它运作完美!