[英]hibernate "No default constructor for entity" created with @Data annotation
I am trying to set up a database table using a JpaRepository.我正在尝试使用 JpaRepository 设置数据库表。 I have the following model class:
我有以下 model class:
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;
}
When I run my application the table is created just fine.当我运行我的应用程序时,表创建得很好。 I have manually added a row to the table, yet when I try to look up the row using
repository.findById
I get the following error:我已经手动向表中添加了一行,但是当我尝试使用
repository.findById
查找该行时,出现以下错误:
org.hibernate.InstantiationException: No default constructor for entity: : com.mypackage.mypackage.model.MyModel
I am confused by the 'no default constructor' error.我对“无默认构造函数”错误感到困惑。 I thought the
@Data
annotation automatically created a constructor for the class?我以为
@Data
注释自动为 class 创建了一个构造函数?
Hibernates doesn't play with with immutable entities, it wants: Hibernates 不使用不可变实体,它想要:
public MyModel() {}
public MyModel() {}
So just remove the final
modifiers so that @Data
generates all this for you.因此,只需删除
final
修饰符,以便@Data
为您生成所有这些。
Ah, that's why it rings a bell, it relates to that other question of yours .啊,这就是它响铃的原因,它与你的另一个问题有关。 So yeah, with Hibernate entities, you can't easily use immutable entities.
所以,是的,使用 Hibernate 实体,你不能轻易使用不可变实体。 You can still add
@AllArgsConstructor
alongside @Data
if you need such a constructor too.如果您也需要这样的构造函数,您仍然可以在
@Data
旁边添加@AllArgsConstructor
。
Edit: As rightfully raised by Andrey B. Panfilov in the comments, @Data
shouldn't be used at all on top of entities.编辑:正如Andrey B. Panfilov在评论中正确提出的那样,@
@Data
根本不应该在实体之上使用。 Quoting Thorben Janssen :引用托本·詹森的话:
The bottom line is that you can use the
@Getter
,@Setter
, and@Builder
annotation without breaking your application.底线是您可以使用
@Getter
、@Setter
和@Builder
批注而不会破坏您的应用程序。 The only Lombok annotations you need to avoid are@Data
,@ToString
, and@EqualsAndHashCode
.您需要避免的唯一 Lombok 注释是
@Data
、@ToString
和@EqualsAndHashCode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.