Monday 9 May 2022

Hibernate Entities in Kotlin

Did a little research what kind of Kotlin classes I should use when creating Entities for the Hibernate framework.

Data classes

Just a short blurp on the requirements that data classes need from [1]:

  • the primary constructor needs to have at least one parameter
  • all primary constructor parameters need to be marked as either val or var
  • data classes cannot be abstract, open, sealed or inner

Hibernate Entities

Just a short blurp on the JPA requirements of entities from [2]

  • The entity class must have a public or protected no-argument constructor.
  • The entity class must be a top-level class.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • The persistent state of an entity is represented by instance variables, which may correspond to JavaBean-style properties. An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.

Conclusion

  • we need to define constructor parameters with var - as they should be mutable
  • we need to specify defaults for every constructor parameter, in order to generate the no-argument constructor
  • Hibernate entities should be "open" in Kotlin (so not final) in order for Hibernate to generate proxies. (this is fixed with the allopen addon in Maven)

So data classes are not a good fit, but a "normal" Kotlin class with just a constructor with annotated vars parameters with default values will work just fine.

References

[1] Kotlin - Data Classes
https://kotlinlang.org/docs/data-classes.html
[2] Hiberante ORM 5.5.9. Final User Guide
https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#entity
Medium.com - Defining JPA/Hibernate Entities in Kotlin
https://medium.com/swlh/defining-jpa-hibernate-entities-in-kotlin-1ff8ee470805