this is where error occured before i try to remove userAddress from UserAddressSet
Code:
if (!getUserAddressSet().contains(userAddress)) throw new IllegalArgumentException("user address does not exist");
So, I added follow code to check if persistentset is doing something weird. And it appeared to be the case. Following snippet inside the removeUserAddress actually throws exception. Which implied that contains should return true.
for (UserAddress o : getUserAddressSet()) {
if(o.equals(userAddress)) {
throw new IllegalArgumentException("object found");
}
}
here is what i do in the test case.
1) create new user object.
2) create a new user address and call the convience method add to the user. then call user update.
3) call the convience method remove from user object with the "same user address object that used was added to the user". and call update.
Code:
public void testUpdateUserAddress_with_required_fields() {
Person person = _objectCreateUtil.getPerson(false);
UserAddress userAddress = _objectCreateUtil.getUserAddress(false); // from previous test.
_objectCreateUtil.setUserAddress(userAddress);
assertNotNull("city is null", userAddress.getCity());
assertNotNull("state is null", userAddress.getState());
assertNotNull("country is null", userAddress.getCountry());
// person.addUserAddress(userAddress);
_userApi.updateObject(person);
_userApi.commit();
assertNotNull("address id is null", userAddress);
}
public void testDeleteUserAddress() {
Person person = _objectCreateUtil.getPerson(false);
UserAddress userAddress = _objectCreateUtil.getUserAddress(false);
assertNotNull("id is null", userAddress.getId());
person.removeUserAddress(userAddress);
_userApi.updateObject(person);
_userApi.commit();
person = _userApi.loadObject(person.getId());
assertEquals("address is not empty", 0, person.getUserAddressSet().size());
}
_objectCreateUtils is used to carry object between different test case.
I am still new to hibernate, so i do not know much about using database key in hashCode/equals can cause problem. I believe that the pitfall is dealing with new object that doesn't have id. That's why I asked in my previous post if it's possible to reserve negative number for new object. This will ensure equals and hashcode always works.
Code:
public boolean equals(Object rhs) {
if (rhs == null)
return false;
if (! (rhs instanceof Person))
return false;
Person that = (Person) rhs;
if (this.getId() == null || that.getId() == null)
return false;
return (this.getId().equals(that.getId()));
}
public int hashCode() {
if (this.hashValue == 0) {
int result = 17;
int idValue = this.getId() == null ? 0 : this.getId().hashCode();
result = result * 37 + idValue;
this.hashValue = result;
}
return this.hashValue;
}