查询外键时是否可以使用二级缓存
Is it possible to make use of 2nd level cache when querying foreign keys
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(...)
?
我终于找到了解决办法。 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;
...
}
完美运行!
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(...)
?
我终于找到了解决办法。 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;
...
}
完美运行!