JPA Onetoone Lazy Misleading

ID

java.jpa_onetoone_lazy_misleading

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

hibernate, jpa, orm

Description

Reports non-owning @OneToOne associations that declare fetch = FetchType.LAZY together with mappedBy. Hibernate cannot proxy the non-owning side of a one-to-one relationship because it must check whether the association is null, which requires a database query. The LAZY hint is silently ignored and the association is always loaded eagerly.

Rationale

Reliability — Developers expect lazy loading but get eager loading, causing unexpected N+1 query problems and degraded performance.

Remediation

Non-compliant code

@OneToOne(fetch = FetchType.LAZY, mappedBy = "parent")
private Child child; // always loaded eagerly

Compliant code

// Option 1: Use @MapsId on the owning side for true lazy loading
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Parent parent;

// Option 2: Accept eager loading on the non-owning side
@OneToOne(mappedBy = "parent")
private Child child;