To show this problem I better use the box example. In real life a box can contain items. However a box can also be considered as an item itself. Therefore if I want to do some programming taking this example I would have to code something as follows:
Code:
public class Item{
private long id;
private string name;
private double weight;
// Constructor and other methods.
}
public class Box extends Item{
private List<Item> items;
private Box parent;
// Constructor and other methods.
}
Therefore, with the above classes I can have the following code in my application:
Code:
// Initialising all the objects accordingly.
Box childreenRoom = new Box(“Childreen Room”);
Item carpet = new Item (“Carpet”, 1.2);
Item mirror = new Item (“Mirror”, 4.2);
Box toys = new Box(“Edward Toys”);
Item car = new Item(“Ferrari Broken Model”, 2.2);
// Adding items to boxes.
toys.add(carr); // Adding car to toy box.
childreenRoon.add(carpet); // Adding carpet to childreenRoom box.
childreenRoon.add(mirror); // Adding mirror to childreenRoom box.
childreenRoon.add(toys); // Adding toys box in childreenRoom box.
// Saving everything in the database.
boxDAO.persist(childreenRoom);
The above code should compile and work fine. Naturally I am assuming that I have all my hibernate configuration done correctly and that my boxDAO is working properly. What should happen when I save childreenRoom Box is that a new row with the box details will be saved inside the Box table and Item table. The same should happen for the toys Box, while for the carpet, mirror and car Item only a row in the Items table will be created. Am I right so far?
Now the problem I can see only comes if I do the following code:
Code:
Box A = new Box(“A”);
A.add(A);
As you can see in the above box I am adding Box A to Box A, which is something impossible to do in real life. However that is not the bigest problem. Worse then that is that like this you are imposible to create the three of elements inside Box A, since it will enter in an endless loop. The same scenario can be repeated even if doing as follows:
Code:
Box A = new Box(“a”);
Box B = new Box(“b”);
Box C = new Box(“c”);
A.Add(B);
B.Add(C);
C.Add(A);
In the above example, C contains Box A (which again should be impossible). This would mean that my object structure is in an incorrect status.
Having said all the above, so far I did not find anything in the database or in Java that actually tried to prohibit having such an event. That is Doing the above code in Java will work fine.
My question is this; Is there something in Hibernate to actually prohibit an Object having a child object which is also its parent!? I know it is quite hard to understand the issue, but is there some configuration setting on how to avoid allowing such an even happening? Even maybe my making Hibernate throw an exception. Or it is something I have to handle before saving my object structure with Hibernate?
Thanks & Regards,
Sim085