【发布时间】:2020-01-10 00:45:14
【问题描述】:
我想知道 JpaRepository 是否有一种方法可以只更新对象的特定值而不从数据库中获取整个对象。这是我的代码来解释一下:
控制器
@PatchMapping("/{labelKeyUuid}")
@ApiOperation("Update the current version of an existing label key")
fun updateCurrentVersion(@PathVariable labelKeyUuid: UUID,
@RequestBody labelValueUuidRequest: LabelValueUuidRequest) {
val labelValue = labelValueService.findByUuid(labelValueUuidRequest.uuid)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Label value with uuid '\'${labelValueUuidRequest.uuid}\'' not found")
return labelKeyService.updateCurrentVersion(labelKeyUuid, labelValue)
}
服务
fun findByUuid(uuid: UUID) : LabelValueEntity? {
return labelValueRepository.findByIdOrNull(uuid)
}
fun updateCurrentVersion(labelKeyUuid: UUID, labelValue: LabelValueEntity) {
labelKeyRepository.save(labelValue, labelKeyUuid)
}
存储库
@Repository
interface LabelKeyRepository : JpaRepository<LabelKeyEntity, UUID>
JpaRepository 有 save(entity) 方法。我知道我可以通过从数据库中获取对象并使用新对象设置 labelValue 并将其保存到数据库来解决它。有没有更快的方法来做到这一点?
【问题讨论】:
-
JPQL 有一个
UPDATEstatement。除此之外,只要entity is still managed,你就可以修改一个实体,当事务提交时,实体上的更改会被持久化到数据库中。 -
一种更快的方法是不将其保存到数据库中:在事务中修改托管实体,使更改自动持久化。无需调用 save()。
标签: java spring rest spring-boot kotlin