0

I use Android Room library. I have entity Products:

@Entity(tableName = "products", foreignKeys = @ForeignKey(
        entity = Category.class,
        parentColumns = "code",
        childColumns = "category_id"))
public class Product {

    @PrimaryKey(autoGenerate = true)
    private Long id;

    @ColumnInfo(name = "name")
    private String name;

    @ColumnInfo(name = "description")
    private String description;

    @ColumnInfo(name = "category_id")
    private String categoryId;

and second entity.

@Entity(tableName = "categories")
public class Category {

    @PrimaryKey
    @NonNull
    private String code;

    @ColumnInfo(name = "name")
    private String name;

    @Ignore
    private List<Product> products;

When I try insert list of products:

new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                MyApplication.get().getDB().productDao().insertAll(productList);
                return null;
            }
        }.execute();

I get error when try insert products to DB.

Caused by: android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)

How can I fix it?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ip696
  • 6,574
  • 12
  • 65
  • 128

1 Answers1

1

I think this might have to do with the @Ignore annotation in the Category class, where you define the one-to-many owning relationship to Product.

Try and see what happens when you remove the @Ignore annotation. If that does not work, you can also use the @Relation annotation to define a one-to-many relationship. (Source: this SO answer)

jbehrens94
  • 2,356
  • 6
  • 31
  • 59