You need to enable JavaScript to run this app. 使用@Data注解仍遇Hibernate报错:No default constructor for entity
优惠活动
大模型
产品
解决方案
定价
更多

使用@Data注解仍遇Hibernate报错:No default constructor for entity

问题原因

Hibernate实例化实体类时,必须要有无参构造函数(可以是private/protected级别,不强制public)。你的代码中所有字段都用final修饰,Lombok的@Data注解虽然会生成全参构造函数,但由于final字段必须被初始化,无法自动生成无参构造,导致Hibernate无法实例化MyModel,从而抛出InstantiationException。

解决方案

提供三种可行的解决方式:

方法1:移除字段的final修饰符

去掉final后,@Data会自动生成无参构造函数(字段可被默认初始化):

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table
public class MyModel {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String imagePath;
}

方法2:配合Lombok注解保留final字段

如果需要保留final字段,可使用@NoArgsConstructor和@AllArgsConstructor注解,将无参构造的访问级别设为protected(Hibernate可访问非public的无参构造):

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Entity
@Table
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
@AllArgsConstructor
public class MyModel {
    @Id
    @GeneratedValue
    private final int id;
    private final String name;
    private final String imagePath;
}

这种方式既满足Hibernate的实例化要求,又能避免外部随意创建未初始化的实体实例。

方法3:手动编写无参构造函数

不想额外添加Lombok注解的话,直接手动编写无参构造,给final字段设置默认值:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table
public class MyModel {
    @Id
    @GeneratedValue
    private final int id;
    private final String name;
    private final String imagePath;

    // 受保护的无参构造,给final字段赋默认值
    protected MyModel() {
        this.id = 0;
        this.name = "";
        this.imagePath = "";
    }

    // 全参构造函数
    public MyModel(int id, String name, String imagePath) {
        this.id = id;
        this.name = name;
        this.imagePath = imagePath;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:09:16