Pihentagy
10/14/2024, 1:59 PMŁukasz Pięta
10/14/2024, 11:04 PMEntity
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 enoughPihentagy
10/16/2024, 3:57 PMPihentagy
10/16/2024, 3:57 PMŁukasz Pięta
10/16/2024, 8:54 PMequals
/ 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.Pihentagy
10/17/2024, 6:38 AMIf 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.