Kotlin data class with spring jpa

I have read the spring guide with kotlin and its says data class for JPA is not recommended

but i am quite confused after seeing some tutorials and video using data class for JPA

did spring find a way to deal with data class in new versions?

2 answers

  • answered 2021-02-24 05:22 Jens Schauder

    You can use Kotlin for Spring Data entities. This is true for all Spring Data modules including JPA where Spring Data is not the one doing the mapping, but your JPA implementation does.

    The problem is that all the libraries involved are developed with mainly Java in mind and Kotlin isn't developed with Hibernate or Spring Data in mind. Therefore problems are bound to occur. For example Kotlin does generate a lot of stuff that isn't visible for normal users, like special constructors. But this is visible for reflection so in the past we had situations where the developer only sees a single constructor, but Spring Data saw multiple constructors and couldn't decide which one to use.

    So you may use Kotlin, but especially when the next Kotlin version comes a long you might experience some extra pain.

  • answered 2021-02-24 14:44 Erik Finnman

    We have developed several services with Spring and Kotlin and used data classes as e.g. entities. This works fine and leads to a lot less boilerplate. You do, however, need to configure your project with these build options/dependencies to avoid Spring interoperability issues:

    https://kotlinlang.org/docs/all-open-plugin.html