My questions i about storing one-to-many relationship to database (as Programming a one-to-many relationship)
Lets assume the example: we have parent and children. Each parent record can have many childs.
// Db storage:
// id name
public class Parent {
Set<Childs> mChilds;
private long mId;
private String mName;
// etc
public Parent(String name) {
this.mName = name;
}
public static Parent load(id) {
// query database for all Parent attributes
Parent p = new Parent("somename");
// now its time to load set of child (1)
Set<Child> children = Child.loadChildren(p);
}
}
// Db storage
// id name parent_ref
public class Child {
private Parent mParent;
private String mName;
public Child(String name, Parent parent) {
this.mName = name;
this.mParent = parent;
}
// loads a child with specific Id
public static Child load(long id) {
// query db like
Cursor c = db.query("child_table", new String[] {"id", "name", "parent_ref"}, "id = ?", new String[] {String.valueOf(id)});
// now we have a cursor, we can construct child!
// Oh my God! I call Parent.load, that calls loadChildren(3)
return new Child(c.getColumn("name"), Parent.load(c.getColumn("parent_ref")));
}
public static Set<Child> loadChildren(Parent parent){
// fetch all child ids, that given parent has
List<long> childIds = getAllIds(parent);
// for each id load child (2)
Child c = Child.load(childId);
}
}
As you can see, I'd like to load parent by given Id. Parent's load function call child's loadlChildren (call (1)), which calls Child.load(call (2)), which calls Parent.load (3) because it needs to make a reference to parent!
So there are two major questions as Im new to java dev.
1) Are there any workarounds about this problems? what Im doing wrong? 2) My call to loadChildren will create n Parents (n references to n objects) instead of creating references to one object. What should I do?