Issue
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.
Solution
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.
Answered By - Jango