Persistent Collection Fields Must Not Be Arrays
ID |
java.hibernate_no_persistent_arrays |
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 as Java arrays (T[]). Hibernate cannot wrap arrays with its PersistentCollection proxy, so lazy-loading, dirty-checking, and cascade operations will not work correctly. Use a List, Set, or another Collection interface instead.
Rationale
Hibernate tracks collection modifications (add, remove, clear) by wrapping the declared collection type with its own PersistentCollection implementation. Java arrays do not implement the Collection interface and cannot be proxied, which means:
-
Lazy-loading cannot be deferred — the array must be populated immediately.
-
Dirty-checking cannot detect element-level changes.
-
Cascade and orphan-removal semantics are not applied.
// Bad: array-typed persistent field
@Entity
public class Order {
@Id
private Long id;
@OneToMany
private OrderItem[] items;
}
Remediation
Replace the array type with a List, Set, or Collection interface.
// Good: collection-typed persistent field
@Entity
public class Order {
@Id
private Long id;
@OneToMany
private List<OrderItem> items;
}