关系
在DBFlow 中用@Table描述的表,我们可以使用1-1, 1-many, many-to-many来联系它们。
一对一
DBFlow支持多个外键(@ForeignKey),可分别指向不同的表。
(多数情况下,这些字段也添加@PrimaryKey来注解。)
@Table(database = AppDatabase.class)
public class Dog extends BaseModel {
@PrimaryKey
String name;
@ForeignKey(tableClass = Breed.class)
@PrimaryKey
String breed;
@ForeignKey
Owner owner;
}
Stubbed Relationships
考虑到效率的原因,我们强烈推荐你使用@ForeignKey(stubbedRelationship = true)。
这是为什么呢?
这将会预先配置主键的字段到你的表的对象上,其他的字段将不会被设置进去。
如果你想要访问你的对象上全部的内容,你需要调用load()方法。或者使用ModelAdapter去从数据库中加载这个对象。
对于上一个版本的dog,我建议使用Bread bread,代替String bread,这样你持有了bread对象,此时bread有了主键,所以再调用load方法,即可加载bread对象的所有字段了。
每次你调用load方法,dbflow都会从数据库中去加载数据,所以,要按需加载哦。还要注意,若你没有指定Database(foreignKeysSupported = true),调用load也许没有任何影响。
通常来说,对于从数据库中加载出来的每个dog对象,我们也会加载其owner对象一遍,那么问题来了,若我们有50条狗,那我们得加载50次owner啦?这显然不明智,所以针对owner字段,我们最好这样来注解:@ForeignKey(stubbedRelationship = true),如下
@Table(database = AppDatabase.class)
public class Dog extends BaseModel {
@PrimaryKey
String name;
@ForeignKey(stubbedRelationship = true)
@PrimaryKey
Breed breed; // tableClass only needed for single-field refs that are not Model.
@ForeignKey(stubbedRelationship = true)
Owner owner;
}
一对多
在 dbflow中,使用@OneToMany去注解你的model中的方法。
这将使你的model与其它的一堆model建立起联系。
@ModelContainer
@Table(database = ColonyDatabase.class)
public class Queen extends BaseModel {
@Column
@PrimaryKey(autoincrement = true)
long id;
@Column
String name;
@Column
@ForeignKey(saveForeignKeyModel = false)
Colony colony;
List<Ant> ants;
@OneToMany(methods = {OneToMany.Method.ALL}, _variableName = "ants")
public List<Ant> getMyAnts() {
if (ants == null || ants.isEmpty()) {
ants = SQLite.select()
.from(Ant.class)
.where(Ant_Table.queenForeignKeyContainer_id.eq(id))
.queryList();
}
return ants;
}
}
为什么要这样注解呢?
点击这里
多对多
一张表和另外一张表,他们之间是多对多的关系,如何维护这样的关系?
通常是再建立一张表:第三张表来维护二者的关系。
比如:
有一张 User 表,另外一张 Follower 表。
一个user会有多个follower,一个follower也有很多user。所以再搞个第三张表:User_Follower来维护他们的多对多关系。
在dbflow中,多对多(多出来的那张表)是通过代码生成的。


以上代码很轻松的帮你生成了连接表(只要你注解了@ManyToMany)
自定义生成的列的名称
你可以改变生成的列的名称。
- referencedTableColumnName
- thisTableColumnName
多个多对多
你可以指定@MultipleManyToMany来帮你定义多个@ManyToMany。

网友评论