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: foreign key constraint failed (code 19)
There is my entity:
@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;
}
}
A foreign key is nullable if any part is nullable. A foreign key value is null if any part is null.
In short you cannot utilise primary keys that do not have the NOT NULL constraint, when Room builds the schema it is always applied to primary keys.
In Kotlin, this means that title can never be null. To fix this, you just need to change the Entity class a bit, and allow the fields to be Nullable . val type: Int, val url: String?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With