Entity Class Must Declare an Identifier

ID

java.hibernate_entity_must_declare_id

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 do not declare an @Id or @EmbeddedId field. Every JPA entity must have a primary key so that the persistence provider can uniquely identify, persist, and retrieve instances.

Rationale

Without an identifier field, Hibernate cannot map the entity to a database table row. The application will fail at deployment or schema validation time with an AnnotationException indicating that no identifier is specified for the entity.

// Bad: entity without an identifier
@Entity
public class Order {
    private String description;
    private double total;
}

Abstract entity classes and @MappedSuperclass classes are excluded because they typically delegate the identifier to concrete subclasses.

Remediation

Add an @Id field (or @EmbeddedId for composite keys) to the entity class.

// Good: entity with an identifier
@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    private double total;
}