Search code examples
javahibernatecachingone-to-manysingle-instance

hibernate returning same instance for same foreign keys


I have two tables -

PersonType                    Person
----------------------      ------------------
ID  type    pid             pid name 
1   Teacher 1               1   Smith
2   Driver  1               2   David
3   Waiter  2

pid is foreign key of Person. With the hibernate, mapped these two table with many to one.

For java classes -

PersonType 
{
 String id;
 String type;
 Person p;
}


Person
{
 String pid;
 String name;
}

From java code, all PersonTypes were retrieved. After retrieving, changed "Driver" as Smith by calling personType.p.pid= 2. But, both of PersonType ID 1 and 2 are updated. Since PersonType ID 1 and 2 have pid 1, hibernate return the same instance and any changes to one of them is reflecting on both. Please anyone can suggest how to overcome this. Thanks.


Solution

  • I think the way you have modeled this, you should not be doing this:

    personType.p.pid=2

    As you're changing referential data on the hibernate managed models, I think you would want to do this:

    personType.p=smith

    Where smith is a reference to the Person object with ID 1