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

查看:377
本文介绍了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列,因为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天全站免登陆