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.
After declaring JPA entities as Kotlin
data classes in a study group project, lazy loading broke andtoString()threw aStackOverflowError. This post explains how Kotlin’s defaultfinalmodifier anddata classmethods clash with Hibernate, how to configure theall-openandno-argplugins, 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:
Post.member, annotated with@ManyToOne(fetch = FetchType.LAZY), loaded eagerly on every single query.- Printing
post.toString()in a debug log triggered an infinite loop (Post → Member → posts → Post) and crashed with aStackOverflowError. - Adding a new entity to a
HashSetbefore saving it madecontains()returnfalseright aftersave()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 orLazyInitializationException.hashCode(): Changes whenidmoves fromnullto a database-generated value after persistence, soHashSetandHashMapcan no longer find the entity in its original bucket.equals(): ComparesjavaClassstrictly, 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? = nullfor IDs: A non-nullLongcompiles to a primitivelongin bytecode. Spring Data JPA treats a primitive0ID as a transient entity, soLong = 0technically works, butnullexpresses “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. Becauseall-openmakes entity propertiesopen, Kotlin rejectsprivate setat compile time, soprotected setis the practical option. - Write
equals()andhashCode()manually around the ID: Compare effective entity classes withHibernate.getClass()so proxies match real instances, and return a class-level constant fromhashCode()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
| Choice | Fit for entities | Reason |
|---|---|---|
data class entity | Poor fit | Remains final, generates all-field equals/toString, and copy() creates unmanaged instances outside the persistence context |
Regular class + allOpen | Good fit | Supports Hibernate proxies and gives you full control over generated methods |
val property | Immutable fields | Good for association owners and timestamps that never change after creation |
var + protected set | Mutable state | Encapsulates 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
allOpenblock only lists@Entityand omits@MappedSuperclass, properties declared on a shared base class likeBaseTimeEntitystayfinal, preventing proxies from intercepting their getters. Also remember that the syntheticno-argconstructor bypasses property initializers andinitblocks, so any invariant checks placed insideinitwon’t run when Hibernate hydrates an entity from the database.
Checklist
- Did you apply
plugin.springandplugin.jpaand listEntity,MappedSuperclass, andEmbeddableinallOpen? - Is the
HHH000305proxy factory warning completely gone from startup logs? - Are all JPA entities declared as regular
classes instead ofdata classes? - Do
equals()andhashCode()rely on the ID andHibernate.getClass(), and doestoString()exclude association fields? - Are IDs declared as
Long? = nulland mutable fields guarded withprotected set?