繁体   English   中英

并非在每种情况下都使用休眠二级缓存

[英]Hibernate second level cache is not used in every case

使用Spring Boot 2,Spring Data JPA和Hibernate。 我正在尝试对从未更新过的某些实体使用Hibernate的二级缓存。

在我的情况下,实体DocumentType与其他实体相关,因此在查询一种文档类型时,Hibernate进行4条sql查询。 当使用Hibernate二级缓存时,该缓存用于某些实体,但是仍然对数据库进行一个sql查询。 我想了解为什么在某些情况下不使用缓存。

这是我的实体的样子:

@Entity
@Table(name = "document_type")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class DocumentType {

    @Id
    private Long id;

    @Column
    private String subtypeCode;

    @OneToOne(cascade = {CascadeType.ALL})
    private Translation translation;

    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "business", joinColumns = @JoinColumn(name = "document_type_id"))
    @Enumerated(EnumType.STRING)
    @Column(name = "business")
    private Set<Business> businesses;

    @ManyToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "equivalence_id")
    private Equivalence equivalence;
@Entity
@Table(name = "equivalence")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Equivalence {

    @Id
    private Long id;

    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
    @OneToMany(mappedBy="equivalence", fetch = FetchType.EAGER)
    private List<DocumentType> documentTypeList;

当我第一次使用此方法获取文档类型时:

@Repository
public interface DocumentTypeRepository extends JpaRepository<DocumentType, Long> {

    DocumentType findBySubtypeCode(String subtypeCode);

我有以下会话指标:

    1704919 nanoseconds spent preparing 4 JDBC statements;
    33284024 nanoseconds spent executing 4 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    2983589 nanoseconds spent performing 4 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    1313315 nanoseconds spent performing 3 L2C misses;

第二次获取的相同文档类型给出:

    27855 nanoseconds spent preparing 1 JDBC statements;
    4348289 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    14421 nanoseconds spent performing 1 L2C puts;
    182655 nanoseconds spent performing 3 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;

我想第二次使用0个JDBC语句,但事实并非如此。

仅当使用EntityManager.find(...)通过其ID检索实体时,或者在JPA需要获取相关实体时在内部,二级缓存才起作用。 默认情况下,永远不会缓存查询结果。

您需要的是Hibernate查询缓存org.hibernate.cacheable查询提示。 另外,您可以启用Spring缓存并使用@Cacheable@CachePut批注。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM