通过中产阶级与房间的关系

时间:2019-04-16 16:29:12

标签: android relationship android-room android-architecture-components

我正在通过一个处理书籍和作者的应用程序来测试Room。

我创建了一个模型,该模型由以下所述的3个标准实体(书,作者,类别)和两个关系实体(CategoryForBook,AuthorOfBook)组成

@Entity(tableName = "books")
data class Book(
    @PrimaryKey @ColumnInfo val id: Int,
    @ColumnInfo val title: String,
    @ColumnInfo val publicationYear: Int? = null,
    @ColumnInfo val publisher: String? = null,
    @ColumnInfo val coverUrl: String? = null
)

@Entity(tableName = "authors")
data class Author(
    @PrimaryKey @ColumnInfo val id: Int,
    @ColumnInfo val firstName: String,
    @ColumnInfo val lastName: Int?,
    @ColumnInfo val birthDate: Date?,
    @ColumnInfo val nationality: String?,
    @ColumnInfo val biography: String?,
    @ColumnInfo val pictureUrl: String?
)

@Entity(tableName = "categories")
data class Category(
    @PrimaryKey @ColumnInfo val id: Int,
    @ColumnInfo val name: String
)

@Entity(
    tableName = "author_of_book", primaryKeys = ["authorId", "bookId"], foreignKeys = [
        ForeignKey(entity = Author::class, parentColumns = arrayOf("id"), childColumns = arrayOf("authorId")),
        ForeignKey(entity = Book::class, parentColumns = arrayOf("id"), childColumns = arrayOf("bookId"))
    ]
)
data class AuthorOfBook(
    @ColumnInfo val authorId: Int,
    @ColumnInfo val bookId: Int
)

@Entity(
    tableName = "categories_for_books", primaryKeys = ["categoryId", "bookId"], foreignKeys = [
        ForeignKey(entity = Category::class, parentColumns = arrayOf("id"), childColumns = arrayOf("categoryId")),
        ForeignKey(entity = Book::class, parentColumns = arrayOf("id"), childColumns = arrayOf("bookId"))
    ]
)
data class CategoryForBook(
    @ColumnInfo val categoryId: Int,
    @ColumnInfo val bookId: Int
)

由于一本书可以由多位作者撰写,并且具有多个类别,因此我需要多对多关系,因此需要关系实体。

现在,我想检索有关一本书的所有信息,但是由于有此中间表(CategoryForBook和AuthorOfBook),所以我不知道如何编写我的类FullBookInfo。

有没有一种方法可以通过另一个类创建关系,或者可以在到达感兴趣的表(作者和类别)之前使用与中间表的关系?

0 个答案:

没有答案