首页 > 解决方案 > Spring Data JPA - 如何缓存包含在许多其他实体中的实体

问题描述

我使用 Spring Data JPA 从存储库中获取实体。我有一个名为 Category 的特定实体,它可以包含在 Offer、Project 和 User 中。每次我从 JpaRepository 加载其中一些实体时,Spring 都会发出其他请求来获取 Category。因此,合作伙伴实体如下所示:

@Entity
class Project(...) {
    constructor() : this(...)

    @Id
    var id: String = IDGenerator.longId()

    @ManyToMany
    var categories: MutableList<Category> = mutableListOf()
    @ManyToOne
    var mainCategory: Category? = null

    //other fiels
}

类别如下所示:

@Entity
class Category(var name: String,
                var icon: String) {
    constructor() : this("", "")

    @Id
    var id: String = IDGenerator.longId()
    var marker: String = "default-category.png"
    @ElementCollection
    var defaultImg: MutableList<String> = mutableListOf("default.jpg")
}

如何缓存类别并使它们不按 ID 从数据库加载?

PS项目中只有大约40-50个类别。

标签: javaspringkotlinspring-data-jpaspring-cache

解决方案


你想使用休眠“二级缓存”

1 将二级缓存库之一添加到您的 pom.xml 中。我更喜欢 ehcache,但你可以使用任何其他的。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <!--Your hibernate version-->
    <version>5.2.2.Final</version> 
</dependency>

2 开启二级缓存persistence.xml

<properties>
    ...
    <property name="hibernate.cache.use_second_level_cache" value="true"/>
    <property name="hibernate.cache.region.factory_class"
      value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
    ...
</properties>

或者您可以在 application.properties 中进行

spring.data.jpa.hibernate.cache.use_second_level_cache=true
spring.data.jpa.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

3 将@Cacheable 注释添加到您的实体。

@Entity
@Cacheable
class Category(...){
.........
}

这就是一切的开始。Category 将从 DB 中读取一次,并存储在二级缓存中。下一次 Hibernate 将从那里获取它,没有任何新的“选择”。


推荐阅读