房间上可以为空的外键 [英] Nullable foreign key on room

查看:25
本文介绍了房间上可以为空的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would know if that is possible to create a possible null reference on foreign key with room.

目前我的数据库结构是这样的:

For now my database structure is like this :

@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;   
}

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

I would like to be able to insert the following objects :

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)

But the previous insert with null value give this error : FOREIGN KEY constraint failed (Sqlite code 787 SQLITE_CONSTRAINT_FOREIGNKEY)

有没有办法让它成为可能?

Is there a way to make it possible ?

推荐答案

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

Yes, just change foreign key types from long to Long.

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

In Java, long type cannot be null and therefore Room generates this column as NOT NULL. Also, the C class does not have @PrimaryKey specified.

@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;   
}

在 Kotlin 中,Long 类型是非空的.如果要插入可为空的外键,则需要将字段更改为可空类型Long?.

In Kotlin, Long type is non-null. If you want to insert nullable foreign keys, you need to change the fields to nullable type Long?.

@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
    var id: Long = 0
    var foreign_id_a: Long? = null
    var foreign_id_b: Long? = null
}

这篇关于房间上可以为空的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆