我在我的 Android 应用中使用 Room。一张表 (stock_move) 包含多个外键。在某些情况下,我需要插入一个没有 FK (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; 
    } 
} 

请您参考如下方法:

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

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


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!