Hi all! Could someone point me to some best-practi...
# spring
s
Hi all! Could someone point me to some best-practices when it comes to using JPA with kotlin? For example, in java you don't usually call
save()
to persist an update of a changed Entity object and simply update the fields. But in kotlin I'd need to use `var`s for that, which seems meh... So how do you do it? Because AFAIK calling
save
to persist updates is considered a bad practice and forces unnecessary flushes.
r
this article gives some good pointers regarding JPA and data classes: https://jpa-buddy.com/blog/best-practices-and-common-pitfalls/ However, in my own personal experience, I would say that if you really dislike `var`s, try to stay away from JPA. Although to some extent in some cases it can work with immutable data classes, it can lead to some nasty bugs in many other cases. So I tend to accept the fact that it works better with `var`s and just keep the usage of these classes contained within the persistence layer. Regarding the
save
method in JPA repositories, I recommend this article: https://vladmihalcea.com/best-spring-data-jparepository/
👍 1
s
Thanks a lot for the links, @Riccardo Lippolis.
r
The short answer is that JPA entities are mutable by nature. That's why e.g. Java records or classes built using the
immutables
library don't lend themselves well to entity classes either. They're contradicting concepts. If you want to use JPA, like @Riccardo Lippolis says, accept mutability and limit it to the persistence layer/module.
👍 1
s
Thanks. Yeah, that's apparently "the way". I'm not sure I can avoid JPA (would need to bring some really good arguments to abandon it), so I guess mutable vars it is
Been playing around with it for a few hours now, and I can see why it needs to be mutable
j
JPA is very stateful. Its not really inline with the direction the industry has been going. I would avoid it
🔥 1
a