【问题标题】:ORMLite many to many relationORMLite 多对多关系
【发布时间】:2013-07-16 09:56:34
【问题描述】:

为了在这两个类之间使用 ORMLite 建立多对多关系:

@DatabaseTable(tableName = "test1")
public class Test1 {
    @ForeignCollectionField
    private ForeignCollection<Test2> test2Collection;
}

@DatabaseTable(tableName = "test2")
public class Test2 {
    @ForeignCollectionField
    private ForeignCollection<Test1> test1Collection;
}

我在创建表时遇到了 ORMLite 的问题,不知道此类之间的外键..

为了建立这种关系,我必须在每个类上添加一个 ForeignDatabaseField,如下所示:

@DatabaseTable(tableName = "test1")
public class Test1 {
    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Test2 test2;
    @ForeignCollectionField
    private ForeignCollection<Test2> test2Collection;
}
@DatabaseTable(tableName = "test2")
public class Test2 {
    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Test1 test1;
    @ForeignCollectionField
    private ForeignCollection<Test1> test2Collection;
}

好像是一种奇怪的方式?

【问题讨论】:

  • 对不起,我不明白这个问题。如果没有一些共享信息,您将如何表示与 Test1 集合相关联的 Test2 的所有权?
  • 是的,我需要链接到第二个对象主键的外键。所以这就是我在第二个例子中所做的......?!

标签: android many-to-many dao ormlite


【解决方案1】:

为了建立这种关系,我必须像这样在每个类上添加一个 ForeignDatabaseField:

对于多对多关系,将对象关联在一起的最佳方式是使用“连接表”。在您的情况下,将有一个名为 Test1Test2Join 或其他名称的第三张表。

@DatabaseTable(tableName = "test1test2join")
public class Test1Test2Join {
    @DatabaseField(generatedId = true)
    private long id;
    @DatabaseField(foreign = true)
    private Test1 test1;
    @DatabaseField(foreign = true)
    private Test test2;
}

有关详细信息,请参阅many-to-many example

【讨论】:

  • 如果我错了,请纠正我,但这(他的第二个例子)不适用于多对多关系。要建立从 Test1 到 Test2 的一对多关系,Test2 可以拥有任意数量的 Test1 对象,但每个 Test1 对象都必须具有对包含它们的 Test2 的引用。现在,您想在另一个方向上做同样的事情:Test1 包含多个 Test2 对象。但是,Test2 只能通过 private Test1 test1 字段引用一个包含它的 Test1 对象(因为您不能为此使用该集合)。好还是不好?
  • 是的,这个答案没有意义@Rauter。我已经重写了。谢谢。
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 2012-02-28
  • 2018-06-15
  • 1970-01-01
  • 2014-10-11
相关资源
最近更新 更多