0

I want to know if JpaRepository has a method to update only a specific value of an object without getting the whole object from the database. This is my code to explain it a bit more:

Controller

@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)
}

Service

fun findByUuid(uuid: UUID) : LabelValueEntity? {
    return labelValueRepository.findByIdOrNull(uuid)
}

fun updateCurrentVersion(labelKeyUuid: UUID, labelValue: LabelValueEntity) {
    labelKeyRepository.save(labelValue, labelKeyUuid)
}

Repository

@Repository
interface LabelKeyRepository : JpaRepository<LabelKeyEntity, UUID>

JpaRepository has save(entity) method. I know i can work around it by getting the object from the database and set the labelValue with the new one and save it to the database. Is there a faster way to do this?

J. Adam
  • 737
  • 1
  • 10
  • 25
  • JPQL has an [`UPDATE` statement](https://javaee.github.io/tutorial/persistence-querylanguage004.html#BNBTK). Other than this, as long as an [entity is still managed](https://javaee.github.io/tutorial/persistence-intro004.html#BNBRC), you can modify an entity and when the transaction is commited, the changes on the entity will be persisted in the database. – Turing85 Sep 07 '19 at 12:55
  • A faster way would be to not save it to the database: modifying a managed entity, inside a transaction, makes the changes automatically persistent. No need to call save(). – JB Nizet Sep 07 '19 at 12:55

1 Answers1

0

If you don’t need to access current state of the object, you can use entityManager.getReference() method. Contrary to entityManager.find() this method won’t invoke a select statement.

entityManager.getReference() is exposed on JPARepository as getOne() method.

Note that objects returned by both methods have automatic dirty checking, you should call find() or getReference() and subsequent modifications in a same transaction, and the changes will be automatically persisted. Use save() on the repository only to persist new entities or attach detached entities.

Read also: When to use EntityManager.find() vs EntityManager.getReference() with JPA

Lesiak
  • 12,048
  • 2
  • 17
  • 41