Heya.
I'm testing an integration testcase (using Spring's AbstractTransactionalDataSourceSpringContextTests class) where I'm creating an Address object and setting its not-null properties one-by-one, testing that it won't save if I've left a not-null field as null.
I was surprised by the following behavior:
Code:
...
Address address = new Address();
address.setStreetAddress1("Street 1");
try {
this.addressDAO.saveOrUpdate(address);
this.addressDAO.flush();
// Since not-null city, state, and zipCode haven't been set, failure.
fail();
} catch (Exception e) { e.printStackTrace(); }
assertNull("Expected a NULL id but instead found: " + address.getId(), address.getId());
...
As expected, an exception was thrown and printed out complaining about not-null properties that were null.
However, what wasn't expected was the assertion failure, with the message: "Expected a null id but instead found: 1"
It is my understanding that Hibernate defines a persistent object to be one whose ID-property is not null; I would expect the object's ID-property to be left null if the save did not go through.
I do understand that I'm swallowing an exception, but in the context of this test, I think it's reasonable -- the rationale is to keep trying to insert it, fixing one property at a time. But since the ID is being set, Hibernate then thinks I'm doing an update, which ultimately fails when all the not-null properties are set because there's no row to update. I can't set the id to null manually, as Hibernate then complains.
I guess I'm curious as to the rationale behind setting the primary key even when the insertion fails.
Thanks,
Jim