Rest 仅当Koltin中的值不为null时才更新

Rest 仅当Koltin中的值不为null时才更新,rest,kotlin,jpa,spring-data-jpa,Rest,Kotlin,Jpa,Spring Data Jpa,因此,我尝试只更新请求响应体中不为null的值。这就是它现在的样子,如果我不发送所有的值,它们就会在数据库中为空。我正在使用Kotlin和JPareposities @PutMapping(value = ["/patient"], produces = ["application/json"]) fun updateClient(@RequestBody client: Client): ResponseEntity<Client>{

因此,我尝试只更新请求响应体中不为null的值。这就是它现在的样子,如果我不发送所有的值,它们就会在数据库中为空。我正在使用Kotlin和JPareposities

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

是否有一种更简单的方法,可以为每个值编写一次副本,并在之前检查其是否不为null?

在不修改当前模型或创建其他帮助器模型/函数的情况下,唯一可以使过程更简单的方法是使用elvis操作符

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

实现这一点的其他方法是创建我们自己的复制函数来忽略输入null,或者创建一个自定义构造函数来忽略输入null。但这需要更多的工作,这取决于模型是否合理,比如我认为不合理的示例模型,如果不修改当前模型或创建其他帮助器模型/函数,只需使用elvis操作符,就可以使过程变得更简单

 val new = old.copy(
        lastName = client.lastName ?: old.lastName,
        firstName = client.firstName ?: old.firstName,
        birthDate = client.birthDate ?: old.birthDate,
        insuranceNumber = client.insuranceNumber ?: old.insuranceNumber
    )
实现这一点的其他方法是创建我们自己的复制函数来忽略输入null,或者创建一个自定义构造函数来忽略输入null。但这将需要更多的工作,这取决于模型是否合理,例如,在我看来没有意义的示例模型,这将是过分的