Should I use Kotlin data class as JPA entity?

12,716

Solution 1

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.

Solution 2

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

Solution 3

That's right: Kotlin Data classes are immutable by default, but that shouldn't stop you from using lazy fetch.

In order to make lazy fetching working as expected, entities should be open. You can use a plugin called Kotlin allopen for that purpose:

plugins {
  ...
  kotlin("plugin.allopen") version "1.3.61"
}

allOpen {
  annotation("javax.persistence.Entity")
  annotation("javax.persistence.Embeddable")
  annotation("javax.persistence.MappedSuperclass")
}

https://plugins.gradle.org/plugin/org.jetbrains.kotlin.plugin.allopen

Share:
12,716
Jango
Author by

Jango

Updated on July 08, 2022

Comments

  • Jango
    Jango almost 2 years

    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.

  • Efriandika Pratama
    Efriandika Pratama over 3 years
    Are u sure with your answer? Kotlin docs said "Data classes cannot be abstract, open, sealed or inner" kotlinlang.org/docs/reference/data-classes.html