When an entity is written in Kotlin and has an init block, the code in this isn't called when the entity is created by JPA (e.g. as the result of a repository query). This results in uninitialized data, and even in non-nullable Kotlin fields having a null value.
@Entity
class User(@Id val userName: String, val firstName: String, val lastName: String) {
@Transient
val propSetByInit: String
init {
propSetByInit = "foo" // In reality this would be calculated at runtime
}
}
When this entity is constructed from a repository query, propSetByInit has a null value, even though it's a non-nullable String
Spring Data isn't creating entity instances. Instantiation is handled by the underlying JPA provider. Looking at the Kotlin code and the provided project, the Kotlin JPA plugin creates a default constructor that is required by JPA. The default constructor is empty and therefore the common initialization code during construction is never invoked. I attached the decompiled and the bytecode view of your User class. I recommend filing a ticket against the Kotlin plugin as clearly the plugin does not consider the init block
Ah, right, so it's down to the plugin. Gotcha. I wasn't sure where exactly in the stack was the missing logic. I'll find where to log an issue with the plugin. Thanks for such a quick response!
Just in case anyone comes across this in future, this has been logged against the Kotlin JPA plugin, and has been reproduced/confirmed by JetBrains, so hopefully it'll get sorted soon enough there.
yonigibbs opened DATAJPA-1687 and commented
When an entity is written in Kotlin and has an
init
block, the code in this isn't called when the entity is created by JPA (e.g. as the result of a repository query). This results in uninitialized data, and even in non-nullable Kotlin fields having a null value.This can be seen in this GitHub repo: https://github.com/yonigibbs/spring-data-jpa-kotlin-init. This contains the following entity:
When this entity is constructed from a repository query,
propSetByInit
has a null value, even though it's a non-nullable StringAffects: 2.2.4 (Moore SR4)
Reference URL: https://github.com/yonigibbs/spring-data-jpa-kotlin-init
Attachments:
The text was updated successfully, but these errors were encountered: