Rule Definition
A primary key value must never change after it's first assigned. Since it is a generated key, it is automatically set by Hibernate, another JPA implementation or by other provider.
The actual behavior when an application tries to modify the value of a primary key is not defined.
Remediation
Set the setter method as private.
Violation Code Sample
------> sample.hbm.xml:
...
<class name="Sample" table="SAMPLE">
<id name="id" column="id" type="long">
<generator class="sequence"/>
</id>
...
</class>
------> Sample.java:
public class Sample {
private long id;
...
public void setId(long id) { // VIOLATION
this.id = id;
}
public Long getId() {
return id;
}
}
Fixed Code Sample
------> Sample.java:
public class Sample {
private long id;
...
private void setId(long id) { // FIXED
this.id = id;
}
public Long getId() {
return id;
}
}
Reference
Hibernate in Action (ISBN 1932394-15-X) p 89
Java Persistence with Hibernate (ISBN 1-932394-88-5) p 163
The Java Persistence API ( ISBN 1-932394-88-5) p 163, 416
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-firstapp-firstclass
http://burtbeckwith.com/blog/?p=53
Related Technologies
JEE
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.