0

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.

2 Answers2

0

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

Alex
  • 2,435
  • 17
  • 18
  • Thanks for your reply. Actually I have a spring MVC UI for it. I loop through the list of personType and show it on the table. And let the user to change person from drop down. So, its a bit too much to do the changes by your way even though that's the correct way. Is there anyway to tell hibernate to return the different instances for same persons ? – user1707282 Jan 23 '15 at 21:56
  • Generally Hibernate likes to do things the Hibernate way, my experience with it was that it was very much a "my way or the highway" framework. I don't use it anymore, primarily due to it's inflexible nature – Alex Jan 23 '15 at 22:00
0

personType.p.pid= 2 this code does not change the Driver to Smith. It changes Smith's id from 1 to 2. What you need to do is what @Alex suggested.

abinsalm
  • 66
  • 8
  • cascade wasn't applied for that relation. so, It does change. But for both of Teacher and Driver become with David since those two are sharing the same objects. Alex is right. I am just looking for a shortcut which makes hibernate to return different instances. Then no code changes at all :-D. – user1707282 Jan 23 '15 at 22:41