David T.
David T.

Reputation: 15

Only update values if they are not null in Koltin

So i try to only update values if they are not null in the response body of my request. This is how it looks at the moment, and if i dont send all the values with it, they just get nulled in the database. Im using Kotlin with JpaRepositories.

@PutMapping(value = ["/patient"], produces = ["application/json"])
fun updateClient(@RequestBody  client: Client): ResponseEntity<Client>{
    val old = repository.findById(client.id).orElseThrow{ NotFoundException("no patient found for id "+ client.id) }

    val new = old.copy(lastName= client.lastName, firstName = client.firstName,
            birthDate = client.birthDate, insuranceNumber = client.insuranceNumber)
    return ResponseEntity(repository.save(new), HttpStatus.OK)
}

This is how the model class looks like

@Entity
data class Client(
        @Id
        val id: String,
        val lastName: String?,
        val firstName: String?,
        val birthDate: Date?,
        val insuranceNumber: Int?
)

Is there a easier way then writing copy once for every value and checking if its not null before?

Upvotes: 0

Views: 479

Answers (1)

AlexT
AlexT

Reputation: 2964

The only thing that comes to mind that might make the process easier without modifying the current model or having to create other helper model/functions would be to use the elvis operator.

 val new = old.copy(
        lastName = client.lastName ?: old.lastName,
        firstName = client.firstName ?: old.firstName,
        birthDate = client.birthDate ?: old.birthDate,
        insuranceNumber = client.insuranceNumber ?: old.insuranceNumber
    )

Other ways of doing this would be to create our own copy function that would ignore input nulls, or a custom constructor that does the same. But that would require more work, and it depends on the model if that makes sense or not, for the example model that would not make sense in my opinion, it would be overkill

Upvotes: 2

Related Questions