【问题标题】:Does JpaRepository has a patch method to update a specific objectJpaRepository 是否有补丁方法来更新特定对象
【发布时间】: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 有一个UPDATE statement。除此之外,只要entity is still managed,你就可以修改一个实体,当事务提交时,实体上的更改会被持久化到数据库中。
  • 一种更快的方法是不将其保存到数据库中:在事务中修改托管实体,使更改自动持久化。无需调用 save()。

标签: java spring rest spring-boot kotlin


【解决方案1】:

如果您不需要访问对象的当前状态,可以使用entityManager.getReference() 方法。与 entityManager.find() 不同,此方法不会调用 select 语句。

entityManager.getReference()JPARepository 上作为getOne() 方法公开。

注意,这两种方法返回的对象都有自动脏检查,你应该在同一个事务中调用find()getReference()以及后续的修改,修改会自动持久化。仅在存储库上使用 save() 以保留新实体或附加分离的实体。

另请阅读: When to use EntityManager.find() vs EntityManager.getReference() with JPA

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多