房间内可空外键

时间:2019-06-07 10:37:17

标签: android database foreign-keys android-room

我会知道是否有可能在带有空间的外键上创建一个空引用。

现在我的数据库结构是这样的:

@Entity(tableName = "A")
class A {
    @PrimaryKey(autoGenerate = true)
    public long id;
}

@Entity(tableName = "B")
class B{
    @PrimaryKey(autoGenerate = true)
    public long id;
}

@Entity(tableName = "C", foreignKeys = {@ForeignKey(entity = A.class, parentColumns = "id", childColumns = "foreign_id_a"), @ForeignKey(entity = B.class, parentColumns = "id", childColumns = "foreign_id_b")})
class C{
    public long id;
    public long foreign_id_a;
    public long foreign_id_b;   
}

我希望能够插入以下对象:

C(id=1, foreign_id_a=1, foreign_id_b=1)
C(id=1, foreign_id_a=null, foreign_id_b=1)
C(id=1, foreign_id_a=1, foreign_id_b=null)

但是前一个具有空值的插入会出现以下错误: FOREIGN KEY约束失败(SQLite代码787 SQLITE_CONSTRAINT_FOREIGNKEY)

有没有办法使之成为可能?

1 个答案:

答案 0 :(得分:1)

是的,只需将外键类型从long更改为Long

在Java中,long类型不能为null,因此Room将此列生成为NOT NULL。另外,C类未指定@PrimaryKey

@Entity(tableName = "C", foreignKeys = {@ForeignKey(entity = A.class, parentColumns = "id", childColumns = "foreign_id_a"), @ForeignKey(entity = B.class, parentColumns = "id", childColumns = "foreign_id_b")})
class C{
    @PrimaryKey
    public long id;
    public Long foreign_id_a;
    public Long foreign_id_b;   
}