Best practice for Hibernate

I’m using Kotlin with Spring and Hibernate. What’s the best practice for Hibernate models with Kotlin? Should I use immutable or mutable classes? Should I use data class? Should I use nullable property for id? Should I use constructor properties or body properties? It seems that there’s absolutely no kotlin-specific support in Hibernate and I did not find popular helper libraries.

Currently I just started and the following class seems to work:

class Account(
        val id: Int?,

        var name: String,

        var password: String,

        var type: AccountType

but the drawback is that I have to use !! every time I’m accessing id. On the other hand I must use something like null to indicate that hibernate must generate id on save.

1 Like

You can move id to the class body if you need it to be generated

class Account(
) {
   @Id @GeneratedValue
   val id = 0 // will be replaced by hibernate

What about UUID / String IDs ?
The “lateinit” keyword does not work, since Hibernate tries to “get the ID” before saving, in order to know whether the Entity is a new one, or should be updated.

Should we keep the IDs as “nullable” ? Or can we, let’s say, initialize them with a dummy value (like an empty String) ?

That happens because you are creating classes that have members in its constructor.

Use this

I already am using the “no-arg” plugin, and the class in question does not have a constructor with members. Anyway, even if it did, why would it change the way Hibernate handles Primary Keys ?