我的问题是关于存储与数据库的一对多关系(如编程一对多关系)
让我们假设这个例子:我们有父母和孩子。每个父记录可以有许多子记录。
// 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 加载父级。Parent的load函数调用child的loadlChildren(call (1) ),它调用Child.load(call (2) ),它调用Parent.load( 3 ),因为它需要对parent进行引用!
所以有两个主要问题,因为我是 java dev 的新手。
1)有没有解决这个问题的方法?我做错了什么?2)我对 loadChildren 的调用将创建 n 个父母(n 个对 n 个对象的引用),而不是创建对一个对象的引用。我该怎么办?