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

syl*_*nvh 7 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

dav*_*idk 7

如果更改数据类型mLocationDestId从变量intInteger架构应该没有NOT NULL约束来生成您的location_dest_id列,因为Integer可为空。

我只在1.1.0-alpha3版本的room中测试过此功能,所以我不知道它是否也可以在1.0.0下使用。