Rule Definition
Hibernate or JPA implementation compares the objects by value not by object identity to determine if the property's persistent state needs to be updated. However, there is one very important exception. Collections are compared by identity. For a property mapped as a persistent collection, you should return exactly the same collection instance from the getter method as Hibernate passed to the setter method. If you don't, Hibernate will update the database, even if no update is necessary, every time the session synchronizes state held in memory with the database.
This doesn't mean you shouldn't return a different collection if you really are replacing the current collection with a new collection with completely different elements. In certain cases, this behavior can even be an opportunity to increase performance.
Remediation
Don't modify the collection.
Violation Code Sample
public class Category {
...
private List theList;
public void setTheList(List myList) {
theList =new ArrayList(myList) ; // VIOLATION
}
public List getTheList() {
return new ArrayList(theList); // VIOLATION
}
...
}
Fixed Code Sample
public class Category {
...
private List theList;
public void setTheList(List myList) {
theList =myList ; // FIXED
}
public List getTheList() {
return theList; // FIXED
}
...
}
Reference
Hibernate in Action (ISBN 1932394-15-X) p 74
The Java Persistence API page 122 - ISBN 1-932394-88-5
Related Technologies
JEE
Technical Criterion
Programming Practices - Modularity and OO Encapsulation Conformity
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.