You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中@MappedSuperclass无参构造函数生成失败求助

问题原因与解决方案

Kotlin JPA插件仅会为标注了**@Entity、@Embeddable、@EmbeddableElement**这类JPA实体相关注解的类自动生成无参构造函数,而你的BaseEntity用的是@MappedSuperclass,不在插件自动处理的范围内,所以没有生成无参构造,导致子类YearEntity调用BaseEntity()时编译报错。

你可以通过以下两种方式解决:

方式1:给BaseEntity手动添加无参构造函数

在父类中显式定义无参构造,委托给带参构造(用默认值占位,JPA会在运行时填充真实ID):

@MappedSuperclass
class BaseEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long,
) {
    // 供JPA使用的无参构造
    constructor() : this(0L)
}

方式2:给BaseEntity的参数设置默认值

直接给id参数指定默认值,Kotlin会自动为类生成无参构造函数:

@MappedSuperclass
class BaseEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0L,
)

两种方式都能让YearEntity的BaseEntity()调用合法,解决编译报错问题。

内容的提问来源于stack exchange,提问作者Hugo Palma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:20:28