使用Room的Android应用 - 如何将外键设置为可为空

8

我正在使用Room技术来开发我的Android应用。其中一个表格(stock_move)包含多个外键。在某些情况下,我需要插入一条没有外键(locationDestId)的stock_move。但是,在这种情况下,SQLite会抛出一个错误:

io.reactivex.exceptions.OnErrorNotImplementedException: foreign key constraint failed (code 19)

以下是我的实体:

@Entity(tableName = "stock_move",
    foreignKeys = {
            @ForeignKey(
                    entity = LocationEntity.class,
                    parentColumns = "id",
                    childColumns = "location_id",
                    onDelete = CASCADE

            ),
            @ForeignKey(
                    entity = LocationEntity.class,
                    parentColumns = "id",
                    childColumns = "location_dest_id",
                    onDelete = CASCADE
            ),
            @ForeignKey(
                    entity = ProductEntity.class,
                    parentColumns = "id",
                    childColumns = "product_id",
                    onDelete = CASCADE
            ),
            @ForeignKey(
                    entity = UomEntity.class,
                    parentColumns = "id",
                    childColumns = "uom_id",
                    onDelete = CASCADE
            )
    }
)
public class StockMoveEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;

    private String name;

    @ColumnInfo(name="product_id")
    private int mProductId;

    @ColumnInfo(name="uom_id")
    private int mUomId;

    @ColumnInfo(name="location_id")
    private int mLocationId;

    @ColumnInfo(name="location_dest_id")
    private int mLocationDestId;

    private int mProductQty;

    public StockMoveEntity(int id, String name, int productId, int uomId, int locationId, int locationDestId, int productQty) {
        this.id = id;
        this.name = name;
        mProductId = productId;
        mUomId = uomId;
        mLocationId = locationId;
        mLocationDestId = locationDestId;
        mProductQty = productQty;
    }
}

1
你找到解决方案了吗? - nAkhmedov
1个回答

10
如果您将mLocationDestId变量的数据类型从int更改为Integer,则模式应生成不带NOT NULL约束的location_dest_id列,因为Integer可为空。
我只在room的1.1.0-alpha3版本中进行了测试,不知道它是否也适用于1.0.0。

实际上,将我的变量类型从int更改为Integer后,它运行得非常好。谢谢。 - sylvainvh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接