Android with Room - 如何将外键设置为可空 [英] Android with Room - How to set a foreign key nullable

查看:60
本文介绍了Android with Room - 如何将外键设置为可空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Room in my Android app. One table (stock_move) contains several Foreign keys. In some case, I need to insert a stock_move without a FK (locationDestId). In this case, SQLite raise an error:

io.reactivex.exceptions.OnErrorNotImplementedException:外键约束失败(代码 19)

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

推荐答案

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

If you change the data type for the mLocationDestId variable from int to Integer the schema should be generated without the NOT NULL constraint for your location_dest_id column since Integer is nullable.

我只用 1.1.0-alpha3 的 room 版本测试过这个,所以我不知道它是否也适用于 1.0.0.

I've only tested this with version 1.1.0-alpha3 of room so I don't know if it works with 1.0.0 as well.

这篇关于Android with Room - 如何将外键设置为可空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆