views:

322

answers:

2
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);
    }
}
A: 

You haven't posted your mappings which makes it impossible to diagnose the problem precisely and your accessors methods seem rather strange (why are you wrapping everything via SpeciaalDiscount.create()? You're even doing it twice on set using example you've posted).

That said, if you did indeed map customer to discount as one-to-one (as you've said in comment), Hibernate behaves as it should (updating the existing "discount" record). Perhaps you should use many-to-one instead (again, hard to say for sure without understanding what you're trying to do).

ChssPly76
A: 

There's probably something going on with the id column auto-incrementing both through Hibernate and through the database. Post up your mapping, and check the column properties in the database. That would help everyone to diagnose the problem.

One other thing. (I'm only familiar with NHibernate, so this may not apply.) To do a row update, usually you have to call Update() or SaveOrUpdate() instead of Save(). Did the call to Save() modify the existing record, or create a new one in the database with id = 2?

Jon Seigel

related questions