Search code examples
springspring-bootkotlinjpa

Spring Boot with Kotlin and Jakarta Persistence: "Not a managed type" error


I'm trying to set up a Spring Boot project using Kotlin and Jakarta Persistence. However, I'm encountering an error when trying to run the application:

Error: Caused by: java.lang.IllegalArgumentException: Not a managed type: class Clue

Project Setup:

  • Spring Boot version: 3.1.3

Clue Entity:

import com.jd.jtrivia.models.Category
import jakarta.persistence.*


@Entity
data class Clue(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    val question: String,
    val answer: String,
    @ManyToOne
    val category: Category
)

I've ensured that:

  • The Clue class is annotated with @Entity from jakarta.persistence.
  • All related dependencies are from the Jakarta namespace.

Project Structure:

  • jtrivia
    • src
      • main
        • kotlin
          • com.jd.trivia
            • JtriviaApplication.kt (@SpringBootApplication)
            • models
              • Clue.kt
              • Category.kt
            • repositories
              • CategoryRepository.kt
              • ClueRepository.kt
              • DatabaseSeeder.kt

Solution

  • Answer:

    It appears the issue was related to an incorrect package import. When working with JPA entities, it's crucial to ensure that the annotations and their associated imports are consistent.

    In my case, the correct import for the JPA annotations is from the com.jd.jtrivia.models package, NOT com.jd.jtrivia.models.Category. The fixed entity declaration is as follows:

    package com.jd.jtrivia.models
    
    import jakarta.persistence.*
    
    @Entity
    data class Clue(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long = 0,
        val question: String,
        val answer: String,
        @ManyToOne
        val category: Category
    )