Entity Class Must Have an Accessible No-Argument Constructor

ID

java.hibernate_no_arg_constructor

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

best-practice, hibernate, orm, reliability

Description

Reports @Entity classes that lack an accessible no-argument constructor (public, protected, or package-private). Hibernate instantiates entities reflectively and requires a no-arg constructor. When all declared constructors take parameters and no no-arg constructor is present, Hibernate fails at runtime with an InstantiationException.

Rationale

The JPA specification mandates that entity classes have a public or protected no-argument constructor. Hibernate also accepts package-private visibility. If a class only declares parameterised constructors, Java does not generate the implicit no-arg constructor, and entity instantiation fails.

// Bad: only parameterised constructors
@Entity
public class Order {
    @Id
    private Long id;
    private String description;

    public Order(String description) {
        this.description = description;
    }
}

Remediation

Add a no-arg constructor with public, protected, or package-private visibility. If the constructor should not be called by application code, make it protected.

// Good: protected no-arg constructor for Hibernate
@Entity
public class Order {
    @Id
    private Long id;
    private String description;

    protected Order() {}

    public Order(String description) {
        this.description = description;
    }
}