Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Kotlin data class as JPA entity?

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.

like image 377
Jango Avatar asked Sep 27 '19 03:09

Jango


Video Answer


2 Answers

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.

like image 132
Jango Avatar answered Sep 23 '22 13:09

Jango


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.)

like image 23
Paulo Merson Avatar answered Sep 21 '22 13:09

Paulo Merson