Nullable foreign key on room(房间上可以为空的外键)
问题描述
我会知道是否有可能在外键上创建一个可能的空引用和空间.
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
}
这篇关于房间上可以为空的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:房间上可以为空的外键


基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01