I'm having trouble implementing an optional association between entities. I have a Customer object with an optional billing Address object. Due to issues with our view technology, the optional child entity - the Address object, in this case - cannot be null.
My first thought was to instantiate an empty Address object in the constructor for the Customer object. The problem with this is that when a Customer entity is retrieved from the database that does NOT have an associated billing address, the Address reference is reset to null.
My second thought was to "lazily" instantiate a new Address object in the getter:
Code:
public Address getBillToAddress(){
if(billToAddress == null){
billToAddress = new Address();
}
return billToAddress();
}
The problem here is that Hibernate thinks the Customer object has been changed and attempts to persist the new, invalid, Address object, which fails.
I need to basically be able to say somehow that the Address reference - even though it is not null - should be treated as if it were null unless some condition is true (in this case that some of its properties have been set). I've tried implementing Lifecycle in both Customer and Address, and I've tried working with an Interceptor.
I'll be happy to post whatever additional code is necessary. Hope this was clear. Any help with this would be greatly appreciated! Thanks in advance.
Brian