java - 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个类别。
解决方案
你想使用休眠“二级缓存”
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 将从那里获取它,没有任何新的“选择”。
推荐阅读
- glsl - GLSL着色器根据用例转换像素颜色
- ffmpeg - 当输入视频是使用 AVComposition 连接的多个剪辑时,ffmpeg HLS 流音频不同步
- arrays - Groovy 语法是否授权多行列表/数组?
- reactjs - setInterval 和 React 功能组件
- javascript - 如何使用 HTML 输入在 JavaScript 中按键过滤字典/对象?
- r - 有没有办法读取 R 中的整个文件文件夹,然后导出为 1 个 excel 工作簿,每个文件输出为一张表?
- java - 读取文件时出错:线程“main”中的异常 java.util.NoSuchElementException:找不到行
- javascript - 根据另一个组件的状态更改 React 组件的可见性
- javascript - GainNode.gain.value 返回属性增益未定义?
- moving-average - 函数 iMA 正在返回与预期不同的返回值 (MQL5)