Java entity - why do I need an empty constructor?

后端 未结 8 828
情歌与酒
情歌与酒 2020-12-08 07:23

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

相关标签:
8条回答
  • 2020-12-08 07:50

    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.

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

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

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

    0 讨论(0)
  • 2020-12-08 07:50

    From the JPA tag, I suppose that you are working with Java beans. Every bean needs to have the following properties:

    1. Getters and setters for all its main instance variables.

    2. An empty constructor.

    3. All its instance variables should preferably be private.

    Thus the statement : "every entity needs an empty constructor".

    0 讨论(0)
提交回复
热议问题