java - 一对多关系

标签 java one-to-many

我的问题是关于存储与数据库的一对多关系(如Programming a one-to-many relationship)

让我们假设一个例子:我们有 parent 和 child 。每个父记录可以有许多子记录。

// 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(调用(1)),它调用Child.load(调用(2)),它调用Parent.load(3)因为它需要引用父级!

作为 Java 开发新手,有两个主要问题。

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

最佳答案

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

我还想看看:Flyweight pattern

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

关于java - 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550241/

相关文章:

java - 在 Postman 上映射<String,String> 键值

java - 在套接字客户端服务器上实现观察者模式

mysql - 在一对多关系上构建 SQL 查询

java - GAE JPA @OneToMany orphanRemoval + Cascade 未按预期工作

mysql - Laravel 5.1 一对多和多对多模型的远程关系

java - 在 Java 中使用 wait() 和 notify() 被阻止

java - 在 Google App Engine, Java 中从 URL 抓取图像

java - 在作为代理工作的 Nginx Ring 处理程序中读取服务器名称

java - OneToMany 外键为空

relationship - 解决数据仓库中的一对多关系?