Entity Class Must Not Import J2EE Web APIs
ID |
java.hibernate_entity_no_j2ee_apis |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
best-practice, code-style, hibernate, orm |
Description
Reports @Entity classes whose compilation unit imports web-layer or J2EE APIs such as javax.servlet., jakarta.servlet., javax.ejb., jakarta.ejb., javax.faces., jakarta.faces., javax.ws.rs., or jakarta.ws.rs.. Entity classes represent persistent domain state and should not depend on presentation or service-layer technologies.
Rationale
Mixing persistence and web-layer concerns in the same class violates separation of concerns and makes the entity impossible to use outside a web container (e.g., in batch jobs, CLI tools, or unit tests). Even an unused import signals that the file was structured with the wrong dependencies in mind and is likely to accumulate more layering violations over time.
The rule covers both single-type imports (import javax.servlet.http.HttpServletRequest) and wildcard imports (import javax.servlet.*).
// Bad: entity class importing servlet API
import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
@Entity
public class Order {
private Long id;
private HttpServletRequest originalRequest; // layering violation
}
Remediation
Move web-layer logic out of the entity. If the entity needs data that originally came from an HTTP request, pass it as a plain value (String, DTO) rather than coupling the entity to the servlet API.
// Good: clean entity with no web-layer imports
import javax.persistence.Entity;
@Entity
public class Order {
private Long id;
private String originIp; // plain data, no servlet dependency
}