customer = // get customer from the current hibernate session
// customer has a discount with database id of 1
Everything is fine until here. But if I call:
discount = SpecialDiscount.create("10%");
customer.setDiscountTo(discount);
session.save(customer);
// customer has a discount with database id of 2 now
How hibernate can update the same discount row with id of 2 even I've set it to another discount value object? Also, I want to prevent "an object with the same identity already exists" errors by detaching the previous one or so. What do you suggest?
// An entity
class Customer {
// one-to-one mapped immutable value object
SpecialDiscount discount;
SpecialDiscount discount() {
return SpecialDiscount.create(this.discount);
}
void setDiscountTo(SpecialDiscount discount) {
this.discount = SpecialDiscount.create(discount);
}
}