spring-guides/tut-spring-boot-kotlin

Question: More details to note - why don't use immutable data classes

jwausle opened this issue · 2 comments

I found Your note here ...

Note: 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.

I use data class with val attributes with JPA annotations and JpaRepository and it seems to work (since a while).

  • DB: postgres 11
  • Spring: 2.3.4
  • Kotlin: 1.5.10
  • Java: 11

Q: Could You give more details to Your note?
Q2: Which pitfalls/limitations exist with immutable data classes?
Q3: This blog post address the same question. At the end with another conclusion. Who is wrong?

I came here to ask the same thing. Spring Boot documentation has links to the following examples :

So one example using JPA uses data class and one doesn't. Both of these are Spring examples, which should it be?

https://github.com/sdeleuze/spring-boot-kotlin-demo is an old personal sample, this one is the reference. The blog post linked explains why immutable data classes are not a good fit with JPA:

To combat this issue, always override equals() and hashCode() when using data classes for entities.

This is absolutely safe to use. However, it almost defeats the purpose of using data classes, as it makes decomposition useless and only uses one field in toString(). A plain old class might be a better option for entities.

So it is possible to use data classes with a lot of care but JPA is not really designed to work with them, hence the choice to use regular mutable classes in this project.