Java entity - why do I need an empty constructor?

Solution 1:

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.

Solution 2:

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.

Solution 3:

Explicitly defining a default constructor is not necessary unless you provide another constructor for the entity. If you provide another constructor, aside from one with the default constructor's signature, the default constructor will not be created.

Since JPA implementations rely upon the existence of a default constructor it is then necessary to include the default constructor that will be omitted.

Solution 4:

As you specified the "JPA" tag, I assume your question applies to JPA only and not empty constructors in general.

Persitence frameworks often use reflection and more specifically Class<T>.newInstance() to instantiate your objects, then call getters/setters by introspection to set the fields.

That is why you need an empty constructor and getters/setters.

See this StackOverflow question about empty constructors in Hibernate.