Entity with Multiple @Id Fields Must Declare @IdClass

ID

java.jpa_entity_multiple_ids

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

hibernate, jpa, orm

Description

Reports @Entity classes that declare more than one @Id field without a corresponding @IdClass or @EmbeddedId annotation. When a composite primary key uses multiple @Id fields, JPA requires an @IdClass to define the composite key type.

Rationale

Without @IdClass, the persistence provider cannot determine the composite key structure and will throw an AnnotationException at deployment time. Each combination of @Id fields must be backed by a separate key class that implements equals() and hashCode() for proper identity semantics.

// Bad: two @Id fields without @IdClass
@Entity
public class OrderLine {
    @Id
    private Long orderId;
    @Id
    private Long productId;
    private int quantity;
}

Remediation

Add an @IdClass annotation referencing a composite key class, or switch to @EmbeddedId with an @Embeddable key class.

// Good: @IdClass declared
@Entity
@IdClass(OrderLineId.class)
public class OrderLine {
    @Id
    private Long orderId;
    @Id
    private Long productId;
    private int quantity;
}