Home > Net >  Kotlin class inheritance throws error for 'gradle build' when used with Spring Data & @Ent
Kotlin class inheritance throws error for 'gradle build' when used with Spring Data & @Ent

Time:11-08

I have a simple entity called Character and looking like this:

import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table

@Entity
@Table(name = "\"character\"")
class Character(
    @Id
    val id: String,
    val name: String,
    position: Position,
) : GameEntity(position) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Character

        if (id != other.id) return false

        return true
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }

    override fun toString(): String {
        return "Character(id='$id', name='$name', position=$position)"
    }

}

It derives from GameEntity that is simply this:

open class GameEntity(
    val position: Position
)

When I run gradle clean build the following Exception is thrown

java.lang.IllegalStateException: No noarg super constructor for CLASS CLASS name:Character modality:OPEN visibility:public superTypes:[com.barbarus.state.entity.GameEntity]:
CONSTRUCTOR IR_EXTERNAL_DECLARATION_STUB visibility:public <> (position:com.barbarus.state.entity.Position) returnType:com.barbarus.state.entity.GameEntity [primary]
    at org.jetbrains.kotlin.noarg.NoArgIrTransformer.getOrGenerateNoArgConstructor(NoArgIrGenerationExtension.kt:66)
    at org.jetbrains.kotlin.noarg.NoArgIrTransformer.visitClass(NoArgIrGenerationExtension.kt:51)
    at org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid$DefaultImpls.visitClass(IrElementVisitorVoid.kt:44)
    at org.jetbrains.kotlin.noarg.NoArgIrTransformer.visitClass(NoArgIrGenerationExtension.kt:33)
    at org.jetbrains.kotlin.noarg.NoArgIrTransformer.visitClass(NoArgIrGenerationExtension.kt:33)
    at org.jetbrains.kotlin.ir.declarations.IrClass.accept(IrClass.kt:55
[...]

CodePudding user response:

It seems to me that you need to add a no-arg constructor to your GameEntity class as follows:

open class GameEntity(val position: String) {
    constructor(): this("")
}

The same might be true regarding Character, because JPA requires a no-arg constructor to be available in the JPA entities:

An entity class must follow these requirements.

  • The class must be annotated with the javax.persistence.Entity annotation.
  • The class must have a public or protected, no-argument constructor. The class may have other constructors.
  • (...)

You can read more at https://docs.oracle.com/javaee/7/tutorial/persistence-intro001.htm.

  • Related