简体   繁体   中英

How to use Room with Java to manage foreign keys

Absolutely new to Room and the new Jetpack App architecture.

I have a database with two normalized tables: Items and Categories. I've created separate classes for both: Item (PK = "rowid") references the primary key from Category (PK = "catid").

My SQLite statement would be:

CREATE TABLE "ITEMS" ( "RowId" INTEGER NOT NULL, "CatId" INTEGER NOT NULL, "ItemName" TEXT NOT NULL, FOREIGN KEY("CatId") REFERENCES "CATEGORIES"("CategoryId") ON UPDATE CASCADE ON DELETE CASCADE, PRIMARY KEY("RowId" AUTOINCREMENT) );

How would I define the foreign keys statement within Item using Room? I've tried:

@Entity(foreignKeys = @ForeignKey(entity = Item.class, parentColumns = "rowid", childColumns ="catid"))

and get the error: @entity not applicable to field.

Just looking for the correct statement syntax and anything else applicable (imports, variables, etc.).

Thank you.

Try this out, this should do the trick

@Entity(tableName = "Categories")
internal class Categories {
    @PrimaryKey
    @ColumnInfo(name = "CategoryId")
    var categoryId = 0
}

@Entity(
    tableName = "Items",
    foreignKeys = [ForeignKey(
        entity = Categories::class,
        parentColumns = ["CategoryId"],
        childColumns = ["CatID"],
        onDelete = ForeignKey.CASCADE,
        onUpdate = ForeignKey.CASCADE
    )]
)
internal class Items {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "RowId")
    var rowid = 0

    @ColumnInfo(name = "CatID")
    var catId = 0
}

This is the SQL statement generated by room

CREATE TABLE IF NOT EXISTS `Items` (`RowId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `CatID` INTEGER NOT NULL, FOREIGN KEY(`CatID`) REFERENCES `Categories`(`CategoryId`) ON UPDATE CASCADE ON DELETE CASCADE )

I do notice some inconsistencies in your question, but you can use the code above and shift what you want to use as a foreign key column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM