JPA: Is it okay to define only the PK of an Entity...
# spring
p
JPA: Is it okay to define only the PK of an Entity as val? Like this? This way id is always non-null, and you cannot mess with the id.
ł
Actually, the key with
Entity
Ids is to have a proper implementation of
equals
and
hashCode
methods. You don't need to hide your Id declaration in the class body—using the primary constructor is, in my opinion, still fine. However, when using Hibernate, you need to be aware of its pitfalls (otherwise, debugging errors in production might be a painful lesson). To continue your example—just because something is immutable or non-nullable in Kotlin code doesn't mean Hibernate won't bypass your class design. This is mainly because Hibernate uses reflection and an empty constructor for object creation behind the scenes. If you're looking for a good explanation of patterns regarding JPA in general or when mixed with Kotlin, feel free to check out my articles where I discuss these topics: • Kotlin and JPA — a good match or a recipe for failure?Hibernate is not so evil - You just don’t know it well enough
p
I hope I understand Hibernate can do anything with the Entities, I just would like to avoid creating invalid Entities from code. Regarding equals / hashCode: if I don't compare or put into hashmap detached entities, should I care about defining hashCode / equals at all? Object identity is fine, since for one PK, there should be at most one attached instance, right?
The main purpose was not hiding (but yeah, why would you manually set the id), but to make it non-nullable
ł
Unfortunately, there are many pitfalls regarding
equals
/
hashCode
, because when you use JPA you should follow the JPA Specification - otherwise no one can guarantee that Hibernate handles your entities properly. To be sure your entity is valid, just follow the specification. If id's nullability bothers you the most, I'd consider generating it in your code instead of the database. By the way, here is a very nice article about common pitfalls of using Kotlin and Hibernate https://jpa-buddy.com/blog/best-practices-and-common-pitfalls/. I strongly recommend going through it before using Kotlin and Hibernate.
p
This article references an article from Thorben Janssen. It says:
If you load your entities in multiple _Session_s or if you work with detached entities, you need to override these methods. In all other cases, it’s better to rely on Java’s default implementation.
👍 1