Say our parent object is Car and child objects are of type Part. Our set mapping would be of the form below
In order to make the changes to the set elements which are of Part type, the order of the update statements must be of this sequence.
Car car = manufacturer.getCar();
//we want to reduce the number of parts say from 10 to 8.
//If the two parts have the ids 9 and 10, then let's remove it
Set parts = car.getParts()
//iterate through the set and grab the objects with ids 9 and 10
Part part9 = (Part)iter.next();//assuming this is the 9th object in the set
Part part10 = (Part)iter.next();//assuming this is the 10th object in the set
parts.remove(part9);
parts.remove(part10);
//persist to database to update the records
saveOrUpdate(car); //this will merge the differences. the database record will //now have 8 rows instead of 10 for the parts. Also, you can use the merge(car) //method and it will work the same way.
//if you want to delete all parts since its no longer produced, just do this
parts.clear();
saveOrUpdate(car); //then there will be zero entries for the parts in the database table
//When it comes to adding a new part, just add the new part object and persist.
Part part11 = new Part();
//...fill properties
parts.add(part11);
saveOrUpdate(car);
No comments:
Post a Comment