Persistent Collection Field Must Be Interface Type
ID |
java.hibernate_collection_field_must_be_interface |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, hibernate, orm, reliability |
Description
Reports persistent collection fields (@OneToMany, @ManyToMany, @ElementCollection) declared with a concrete collection class (ArrayList, HashSet, HashMap, etc.) instead of a Java Collections Framework interface (List, Set, Map, Collection). Hibernate replaces the concrete collection with its own PersistentCollection wrapper at runtime; declaring a concrete type prevents this substitution and breaks dirty-checking.
Rationale
When Hibernate hydrates an entity from the database, it replaces collection fields with its own PersistentBag, PersistentSet, or PersistentMap implementations. If the field is typed as a concrete class like ArrayList, the assignment of a Hibernate proxy triggers a ClassCastException or silently disables change-tracking.
// Bad: concrete collection type
@Entity
public class Project {
@Id
private Long id;
@OneToMany
private ArrayList<Task> tasks;
}
Remediation
Declare the field using the corresponding interface type.
// Good: interface-typed collection
@Entity
public class Project {
@Id
private Long id;
@OneToMany
private List<Task> tasks;
}