Object creation with read only JSON field is not working in Spring Data Rest and Kotlin

68 Views Asked by At

In my Spring Boot application, I want to set fields non nullable in database and Kotlin, but I don't want to make them writable in the Spring Data Rest API.

I prefer to avoid writing a full custom Entity deserializer because I have to reimplement the deserialization for all other fields in bigger Entites.

So what I want to do here is creating the entity in database without having to include the read-only field in JSON, but instead set it in deserializer :

Empty POST request body without name :

{

}

But I still get this error, even with a custom field deserializer :

{
    "cause": {
        "cause": null,
        "message": "Instantiation of [simple type, class models.Cluster] value failed for JSON property name due to missing (therefore NULL) value for creator parameter name which is a non-nullable type\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 1] (through reference chain: models.Cluster[\"name\"])"
    },
    "message": "JSON parse error: Instantiation of [simple type, class models.Cluster] value failed for JSON property name due to missing (therefore NULL) value for creator parameter name which is a non-nullable type"
}
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import jakarta.persistence.*

@Entity
@Table(name = "cluster", schema = "public")
class Cluster(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,

    @Column(nullable = false, unique = true)
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @JsonDeserialize(using = CustomFieldDeserializer::class)
    var name: String,
)
)

Here is the code :

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import org.springframework.boot.jackson.JsonComponent

@JsonComponent
class CustomFieldDeserializer : StdDeserializer<String>(String::class.java) {

    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): String {
        return "Test Name"
    }
}
0

There are 0 best solutions below