Video in progress

Why does an entity class have to have a no-arg constructor?

When Hibernate reads a row from the database, it doesn't know which constructor to call or with what arguments. It creates an empty object with the no-arg constructor and then fills in the fields through reflection. Proxy classes rely on that constructor too.

📖 Answer

The JPA specification requires a public or protected no-arg constructor. protected is better: Hibernate can use it, but regular code can't accidentally create an incomplete object.

@Entity
public class Account {
    @Id @GeneratedValue
    private Long id;
    private String iban;

    protected Account() { }               // for Hibernate only

    public Account(String iban) {         // for business code
        this.iban = Objects.requireNonNull(iban);
    }
}

If the constructor is missing, the error shows up at runtime, not at compile time: "No default constructor for entity". Sometimes only when a lazy proxy gets created, so the first test passes and the error appears later.

If you use Lombok: @NoArgsConstructor(access = AccessLevel.PROTECTED).

In some cases Hibernate can actually create objects another way, but don't rely on that. The specification requires the constructor.