I am developing with Kotlin and JPA recently. I use Kotlin data class as JPA @Entity class.
But now, There comes some problem with relation
@ManyToOne(fetch = FetchType.LAZY, optional = true)
The lazy fetching doesn't work with data class.
I have learned that Kotlin data class is default to be 'final' so that Hibernate can't generate proxy for them.
I wonder is this a mistake to use Kotlin data class as JPA @Entity class or there is other ways to make the lazy fetching work properly with data class.
This Spring official guides shows we shouldn't use kotlin data class with spring-data-jpa.
What they saying:
Here we don’t use data classes with val properties because JPA is not designed to work with immutable classes or the methods generated automatically by data classes. If you are using other Spring Data flavor, most of them are designed to support such constructs so you should use classes like data class User(val login: String, …) when using Spring Data MongoDB, Spring Data JDBC, etc.
Another reason not to use data classes: JPA entities can form a class hierarchy. A data class cannot be open
, that is, cannot have subclasses.
(Here's the best guide on using JPA+Hibernate with Kotlin I found.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With