Android with Room - 如何设置外键可空

时间:2018-02-22 17:37:21

标签: android-sqlite android-room

我在Android应用中使用Room。一个表(stock_move)包含几个外键。在某些情况下,我需要插入一个没有FK(locationDestId)的stock_move。在这种情况下,SQLite会引发错误:

  

io.reactivex.exceptions.OnErrorNotImplementedException:外键约束失败(代码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 个答案:

答案 0 :(得分:3)

如果您将mLocationDestId变量的数据类型从int更改为Integer,那么应该生成架构,而location_dest_id列的Integer列不会生成NOT NULL约束event.eventIdentifier 1}}可以为空。

我只测试了1.1.0-alpha3版的房间,所以我不知道它是否适用于1.0.0。