Java实体 - 为什么我需要一个空构造函数? [英] Java entity - why do I need an empty constructor?

查看:1233
本文介绍了Java实体 - 为什么我需要一个空构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来很愚蠢,
但为什么我需要在 @Entity 中定义一个空构造函数?

This might sound stupid to you, but why do I need to define an empty constructor in my @Entitys?

我看到的每个教程都说:每个实体都需要一个空的构造函数。

Every tutorial I saw said : every entity needs an empty constructor.

但是Java总是给你一个默认的隐形空构造函数(如果你不喜欢的话)重新定义一个。)

But Java always give you a default invisible empty constructor (if you don't redefine one).

谢谢。

我认为存在语义问题。
我对需要的理解是写的。

I think there is a semantic problem. What I understood by "need" was write.

含义:总是在你的实体中写一个空的构造函数。

Meaning: always write an empty constructor in your entity.

示例:

@Entity
public class MyEntity implements Serializable {

   @Id
   private String str;

   public MyEntity(){}

   //here getter and setter
}

但是当你不重新定义它时,Java总会给你这个空的构造函数(用参数写另一个)。

But Java always gives you this empty constructor when you don't redefine it (write an other one with parameters).

在这种情况下编写这个空构造函数似乎没用。

In this case writing this empty constructor seems useless.

推荐答案

需要一个空构造函数来通过你的反射来创建一个新实例持久性框架。如果您没有为该类提供任何其他带有参数的构造函数,则不需要提供空构造函数,因为每个默认值都会得到一个。

An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.

您还可以使用@PersistenceConstructor注释,如下所示

You can also use the @PersistenceConstructor annotation which looks like following

@PersistenceConstructor
public Movie(Long id) {
    this.id = id;
}

如果您的项目中存在Spring Data,则初始化您的实体。因此,您也可以避免使用空构造函数。

to initialise your entity if Spring Data is present in your project. Thus you can avoid the empty constructor as well.

这篇关于Java实体 - 为什么我需要一个空构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆