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 加载父级。Parent的load函数调用child的loadlChildren(call (1) ),它调用Child.load(call (2) ),它调用Parent.load( 3 ),因为它需要对parent进行引用!

所以有两个主要问题,因为我是 java dev 的新手。

1)有没有解决这个问题的方法?我做错了什么?2)我对 loadChildren 的调用将创建 n 个父母(n 个对 n 个对象的引用),而不是创建对一个对象的引用。我该怎么办?

4

1 回答 1

0

为什么不实现某种缓存系统(可能使用Java HashMap),您可以在其中放置父对象及其子对象,而不是加载它们,仅在它们尚未在缓存中时才加载它们?如果它们已经在缓存中,请获取对它们的引用。

我还想看看:Flyweight 模式

或者我能想到的另一种解决方案是在父类中实现另一种方法:类似于“loadOnlyParent()”,它只加载父类(如果尚未加载)而不加载子类。并且仅在必要时实现子项的延迟加载(如果尚未加载)。

于 2012-11-25T10:53:38.280 回答