Kotlin › Practice

Designing Kotlin JPA entities with all-open and no-arg

Configure kotlin-spring and kotlin-jpa for Kotlin JPA entities, avoid data class pitfalls, and set clear rules for val/var and nullable IDs.

Designing Kotlin JPA entities with all-open and no-arg

After declaring JPA entities as Kotlin data classes in a study group project, lazy loading broke and toString() threw a StackOverflowError. This post explains how Kotlin’s default final modifier and data class methods clash with Hibernate, how to configure the all-open and no-arg plugins, and the entity rules I use now.

Tested with Spring Boot 3.1.4, Kotlin 1.9.10, Hibernate ORM 6.2, and Java 17.

The problem

While porting a bulletin board API to Kotlin for a university study project, I declared every JPA entity as a data class because it looked clean and idiomatic. At first the endpoints seemed fine, then three bugs showed up one after another:

  1. Post.member, annotated with @ManyToOne(fetch = FetchType.LAZY), loaded eagerly on every single query.
  2. Printing post.toString() in a debug log triggered an infinite loop (Post → Member → posts → Post) and crashed with a StackOverflowError.
  3. Adding a new entity to a HashSet before saving it made contains() return false right after save() completed.

Looking back at the startup logs, Hibernate had already printed HHH000305: Could not create proxy factory. I brushed past that warning at first, and it turned out to be the exact reason lazy loading failed.

Root cause

Kotlin classes and their members are final by default. Hibernate implements lazy loading by generating a runtime proxy subclass with ByteBuddy. If the entity class is final, ByteBuddy can’t subclass it, so Hibernate logs HHH000305 and falls back to eager loading. Opening the class alone isn’t enough either—every property getter that a proxy needs to intercept must also be open.

Declaring an entity as a data class adds another set of conflicts because the compiler auto-generates equals(), hashCode(), and toString() from every primary constructor property:

  • toString(): Walks bidirectional associations into infinite recursion, and touches lazy fields during logging, causing extra SQL queries or LazyInitializationException.
  • hashCode(): Changes when id moves from null to a database-generated value after persistence, so HashSet and HashMap can no longer find the entity in its original bucket.
  • equals(): Compares javaClass strictly, which fails when one side is a Hibernate proxy subclass and the other is the concrete entity class.

Finally, the JPA specification requires a no-arg constructor so the provider can instantiate entities via reflection. A Kotlin class with required primary constructor parameters doesn’t have one unless you add it or generate it at compile time.

flowchart TD
    A["Kotlin entity (final by default)"] --> B["kotlin-jpa: adds no-arg constructor"]
    B --> C["allOpen: opens class and members"]
    C --> D["Hibernate creates ByteBuddy proxy"]
    D --> E["LAZY associations work as expected"]

The fix: Gradle plugin setup

kotlin("plugin.spring") is a preset for the all-open compiler plugin, and it only opens classes annotated with Spring stereotypes like @Component, @Transactional, and @Async. JPA’s @Entity isn’t on that list, so you have to register JPA annotations in an explicit allOpen block. Meanwhile, kotlin("plugin.jpa") wraps the no-arg compiler plugin and generates parameterless constructors for @Entity, @Embeddable, and @MappedSuperclass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// build.gradle.kts
plugins {
    id("org.springframework.boot") version "3.1.4"
    id("io.spring.dependency-management") version "1.1.3"
    kotlin("jvm") version "1.9.10"
    kotlin("plugin.spring") version "1.9.10"
    kotlin("plugin.jpa") version "1.9.10"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    runtimeOnly("com.h2database:h2")
}

allOpen {
    annotation("jakarta.persistence.Entity")
    annotation("jakarta.persistence.MappedSuperclass")
    annotation("jakarta.persistence.Embeddable")
}

The constructor generated by kotlin-jpa is a synthetic constructor. You can’t call it directly from Kotlin or Java source code; Hibernate invokes it through reflection only. Keep in mind that this synthetic constructor skips property initializers, so non-null Kotlin properties temporarily hold null until Hibernate populates the fields from the database row.

Entity design rules

Once the compiler plugins were in place, I switched every entity to a regular class and followed three guidelines:

  • Use Long? = null for IDs: A non-null Long compiles to a primitive long in bytecode. Spring Data JPA treats a primitive 0 ID as a transient entity, so Long = 0 technically works, but null expresses “not persisted yet” directly in the type system without relying on magic numbers.
  • Encapsulate mutable state with var + protected set: Block arbitrary external writes and route state changes through explicit domain methods. Because all-open makes entity properties open, Kotlin rejects private set at compile time, so protected set is the practical option.
  • Write equals() and hashCode() manually around the ID: Compare effective entity classes with Hibernate.getClass() so proxies match real instances, and return a class-level constant from hashCode() so the hash stays stable before and after persistence.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// src/main/kotlin/com/example/board/member/Member.kt
package com.example.board.member

import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.Hibernate

@Entity
@Table(name = "member")
class Member(
    name: String,
    email: String,
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
        protected set

    @Column(nullable = false, length = 50)
    var name: String = name
        protected set

    @Column(nullable = false, unique = true)
    var email: String = email
        protected set

    fun rename(newName: String) {
        require(newName.isNotBlank()) { "Name must not be blank." }
        this.name = newName
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
        other as Member
        return id != null && id == other.id
    }

    override fun hashCode(): Int = Hibernate.getClass(this).hashCode()

    override fun toString(): String = "Member(id=$id, name=$name)"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/main/kotlin/com/example/board/post/Post.kt
package com.example.board.post

import com.example.board.member.Member
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne

@Entity
class Post(
    title: String,
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "member_id")
    val member: Member,
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
        protected set

    var title: String = title
        protected set

    override fun toString(): String = "Post(id=$id, title=$title)"
}

Leaving association fields out of toString() eliminates both circular recursion and accidental lazy initialization during logging. After applying these changes, the HHH000305 warning vanished on startup, and printing post.member.javaClass confirmed Hibernate had injected a Member$HibernateProxy$... proxy instance.

Trade-offs and when not to use data classes

ChoiceFit for entitiesReason
data class entityPoor fitRemains final, generates all-field equals/toString, and copy() creates unmanaged instances outside the persistence context
Regular class + allOpenGood fitSupports Hibernate proxies and gives you full control over generated methods
val propertyImmutable fieldsGood for association owners and timestamps that never change after creation
var + protected setMutable stateEncapsulates updates so callers must go through domain methods

This doesn’t mean you should avoid data class across your entire Spring Boot codebase. It still fits request and response DTOs, read-only query projections, and @Embeddable value objects where structural equality across all fields is the whole point. Skip data class whenever you’re modeling entities compared by identifier, classes holding lazy associations, or stateful objects tracked by the JPA persistence context.

Warning: If your allOpen block only lists @Entity and omits @MappedSuperclass, properties declared on a shared base class like BaseTimeEntity stay final, preventing proxies from intercepting their getters. Also remember that the synthetic no-arg constructor bypasses property initializers and init blocks, so any invariant checks placed inside init won’t run when Hibernate hydrates an entity from the database.

Checklist

  • Did you apply plugin.spring and plugin.jpa and list Entity, MappedSuperclass, and Embeddable in allOpen?
  • Is the HHH000305 proxy factory warning completely gone from startup logs?
  • Are all JPA entities declared as regular classes instead of data classes?
  • Do equals() and hashCode() rely on the ID and Hibernate.getClass(), and does toString() exclude association fields?
  • Are IDs declared as Long? = null and mutable fields guarded with protected set?
This post is licensed under CC BY 4.0 by the author.