如何使用Android Room创建一个包含两个或多个外键的表?

JP *_*ura 8 sqlite android android-sqlite android-room

在此输入图像描述

根据实体关系模型之间的关系,tbl_post并且tbl_category可以使用指定房间持久性库如下:

@Entity(foreignKeys = @ForeignKey(
    entity = TblPost.class,
    parentColumns = "id",
    childColumns = "tbl_post_id")
)
class TblPostCategory {
    @PrimaryKey
    public String id;

    @ColumnInfo(name = "user_id")
    public String postId;
}
Run Code Online (Sandbox Code Playgroud)

但是TblPostCategory取决于两个外键:post_idcategory_id来自TblPostTbCategory.

如何使用房间注释描述关系?

joa*_*o86 24

TblCategory.java

@Entity
class TblCategory {
    @PrimaryKey
    @ColumnInfo(name="cat_id")
    public String id;

    @ColumnInfo(name = "cat_name")
    public String name;
}
Run Code Online (Sandbox Code Playgroud)

TblPost.java(缺少外键引用,但对于这种情况并不重要)

@Entity
class TblPost {
    @PrimaryKey
    @ColumnInfo(name="post_id")
    public String id;

    public String title, content, create_time, author_id;
}
Run Code Online (Sandbox Code Playgroud)

TblPostCategory.java

@Entity(foreignKeys = {
    @ForeignKey(
        entity = TblPost.class,
        parentColumns = "post_id",
        childColumns = "tbl_post_id"
    ),
    @ForeignKey(
        entity = TblCategory.class,
        parentColumns = "cat_id",
        childColumns = "tbl_category_id"
    )
})
class TblPostCategory {
    @PrimaryKey
    @ColumnInfo(name="tbl_post_id")
    public String id;

    @ColumnInfo(name = "tbl_category_id")
    public String categoryId;
}
Run Code Online (Sandbox Code Playgroud)

  • @yalematta 您尝试做的是“违反”数据库建模规则。这是一种“多对多”关系“(n:m)”的情况。阅读:http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php。然而,如果你想将 `List<Post>` 添加到 `tbl_category`,你不需要在 `tbl_post` 中定义外键。你只需要为 `Post` 对象定义 `Converters`,因为 Room 只接受原始类型。看到这个:https://developer.android.com/training/data-storage/room/referencing-data.html (2认同)