HQL/JPQL Cartesian Product Without JOIN

ID

java.hibernate_unaware_cartesian_product

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:400, hibernate, orm, reliability

Description

Reports HQL/JPQL queries passed to createQuery or createNativeQuery that reference multiple root entities in the FROM clause without an explicit JOIN. Such queries produce a Cartesian product (cross join) that typically returns exponentially more rows than intended, causing severe performance degradation or out-of-memory errors.

Rationale

A query like SELECT u, o FROM User u, Order o returns every combination of every user with every order. For N users and M orders, the result set has N * M rows. This is almost never the developer’s intent and can bring both the database and the application to a halt.

// Bad -- Cartesian product of User x Order
em.createQuery("SELECT u, o FROM User u, Order o WHERE u.id = o.userId");

Remediation

Use explicit JOINs to define the relationship between entities:

// Good -- explicit JOIN
em.createQuery("SELECT u FROM User u JOIN u.orders o WHERE o.total > 100");