1対多の関係をデータベースに保存することに関する私の質問(1対多の関係のプログラミングとして)
例を想定してみましょう: 親と子がいます。各親レコードは、多くの子を持つことができます。
// 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);
}
}
ご覧のとおり、指定された ID で親をロードしたいと思います。親のロード関数は、子の loadlChildren (call (1) ) を呼び出します。これは、親への参照を作成する必要があるため、Parent.load ( 3 )を呼び出す Child.load(call (2) ) を呼び出します。
したがって、私はJava devを初めて使用するため、2つの大きな質問があります。
1) この問題に対する回避策はありますか? 私は何を間違っていますか?2) 私の loadChildren への呼び出しは、1 つのオブジェクトへの参照を作成する代わりに、n 個の親 (n 個のオブジェクトへの n 個の参照) を作成します。私は何をすべきか?