Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jwausle opened this issue Oct 26, 2021 · 2 comments
Closed

Comments

@jwausle
Copy link

jwausle commented Oct 26, 2021

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?

@busches
Copy link

busches commented Feb 19, 2022

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?

@sdeleuze
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants