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
1 Like

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 ?

Well from your example you are creating a class with a primary constructor.

The no-arg plugin enables the generation of no-arg constructors only for specific annotations. You should add the @Entity annotation to those using Gradle.

Otherwise use the JPA plugin that already does that out of the box.

Ha, I was not the original owner of this question :slight_smile:

My class looks like this :

class ConnectableUser
    open var userId: String = "" 

And I’m not sure whether I should keep “userId” as nullable (with a String?), or if I should initialize with a dummy value (like I did, with an empty String)

In this example there is no primary constructor with members (and I am using no-arg plugin)

I believe there is no need for defaults or nulls as long as the schema reflects the entity definition (at least for nulls), but try to compile and run a meaningful example! Let us know :slight_smile: