Identifier Setter Should Be Private
ID |
java.hibernate_private_identifier_setter |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, hibernate, orm, reliability |
Description
Reports public or protected setter methods for @Id fields. The entity identifier is managed by the persistence provider and should not be modified by application code. Making the setter private or package-private signals this contract and prevents accidental identifier changes.
Rationale
Modifying an entity’s identifier after it has been persisted breaks the identity contract that Hibernate relies on for the first-level cache (persistence context). Publicly exposing the setter invites accidental misuse, especially during merge or detach/reattach workflows.
// Bad: public setter allows callers to change the id
@Entity
public class Order {
@Id
private Long id;
public void setId(Long id) {
this.id = id;
}
}