为了用 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;
}
好像是个奇怪的方法?
最佳答案
In order to make this relation do I have to add a single ForeignDatabaseField on each class like that:
对于多对多关系,将对象关联在一起的最佳方式是使用“连接表”。在您的情况下,会有一个名为 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 .
关于android - ORMLite 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17673461/