|
We have following Models
public class FruitCollection {
Integer id;
Integer version;
List<Fruit> fruits;
}
abstract class Fruit {
Integer id;
Integer version;
}
class Apple extends Fruit {
Integer vitamin;
}
class Orange extends Fruit {
String taste;
}
class Mango extends Fruit {
boolean juice;
}
All the three fruit classes have unique properties (thats why we have three subclasses). There is one-many relation between FruitCollection and Fruit. In addition, we have also set the discriminitor value for each subclass as we are using table-per-hirerachy approach.
As you can see from the below code snippet...
FruitCollection collection = new FruitCollection();
Apple apple1 = new Apple();
Orange orange1 = new Orange();
collection.getFruits().add(apple1);
collection.getFruits().add(orange1);
hibernateSession.save(collection);
//open a new session
FruitCollection collection1 = (FruitCollection) hibernateSession.load(FruitCollection.class, 10L);
Integer appleId = collection1.getFruits().get(0).getId();
Integer orangeId = collection1.getFruits().get(1).getId();
collection1.getFruits().clear();
Mango mango1 = new Mango();
mango1.setId(appleId);
Mango mango2 = new Mango();
mango2.setId(orangeId);
collection1.getFruits().add(mango1);
collection1.getFruits().add(mango2);
hibernateSession.update(collection1);
...we expected the new object to be persisted in the DB however with the same ID that we have set explicitely. This does not happen. The old objects are removed and new objects get created with new Id's.
We would like preserve Id for instance of Fruit on every update on FruitCollection. Is it anyways possible to have different objects of objects however with the same id in the DB.
|