如何使用Android Room创建带有两个或更多外键的表? [英] How to create a table with a two or more foreign keys using Android Room?

查看:1142
本文介绍了如何使用Android Room创建带有两个或更多外键的表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据实体关系模型tbl_category可以使用房间持久性库指定,如下所示:

According the entity-relationship model, the relationship between tbl_post and tbl_category could be specified using Room Persistency Library as follows:

@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;
}

但是TblPostCategory依赖于两个外键:TblPostTbCategory中的post_idcategory_id.

However TblPostCategory depends on two foreign keys: post_id and category_id from TblPost and TbCategory.

应如何使用会议室注释来描述这种关系?

How the relationship should be described using Room annotations?

推荐答案

TblCategory.java

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

    @ColumnInfo(name = "cat_name")
    public String name;
}

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

TblPost.java (It is missing the foreign key reference but it is not important for the case)

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

    public String title, content, create_time, author_id;
}

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;
}

这篇关于如何使用Android Room创建带有两个或更多外键的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆