Java entity - why do I need an empty constructor?

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

This statement is true only when you don't provide any constructor in your class. If an argument constructor is provided in your class, then JVM will not add the no-argument constructor.


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.

Tags:

Java

Jpa

Entity