Welcome to OStack Knowledge Sharing 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 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...