Hello,
I habe a one to many relation ship between Customer and Contact and Customer and Bank.
Code:
n
1 |------------Contact
Customer <----------|
|------------Bank
1 n
Now I have a method called mergeCustomer (merges existing customer and customer in parameter) in one of my DAO- classes. In this method I will set the (existing)customer for the banks and the contacts to prevent the Exception "cannot insert NULL into CUSTOMER_ID":
Code:
@Override
public Customer mergeCustomer(final Customer customer) {
for (final Iterator<BankAccount> iterator = customer.getBankAccounts().iterator(); iterator.hasNext();) {
final BankAccount bankAccount = iterator.next();
if (bankAccount.getCustomer() == null) {
bankAccount.setCustomer(customer);
}
}
for (final Iterator<Contact> iterator = customer.getContacts().iterator(); iterator.hasNext();) {
final Contact contact = iterator.next();
if (contact.getCustomer() == null) {
contact.setCustomer(customer);
}
}
Customer customerChanged = this.merge(customer); // HibernateDAOBase == this
return customerChanged;
}
In my JUnit TEST- class I invoke this method like this:
Code:
Bank bank = new Bank();
bank .setBankName("new bank");
// bank .setCustomer(customer); // must!! be done before add
customerSaved.getBanks().add(bank );
// 2. new contact
final Contact contact = new Contact();
contact.setFirstName("Vladimir");
// contact.setCustomer(customer); // must!! be done before add - strange
customerSaved.getContacts().add(contact);
final Customer customerChanged = customerDAO.mergeCustomer(customer);
What is strange for me is, when
Code:
bankAccount.setCustomer(customer);
and
contact.setCustomer(customer);
are active (not commented out) than everything works fine, when th two lines are not active, than I get an exception:
Code:
Cannot insert NULL into column CUSTOMER_ID of Bank
although I set the customer in my DAO class before invoking merge.
Does anybody have any idea why this happens.
It looks like that all has to be set into th brand new object, after