Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - 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)

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...