简体   繁体   中英

Multiple Tables In Android Room Database

I wonder how to have multiple tables and using relations in the android room database?? I need a little bit of explanation or if you have a good tutorial, I will appreciate

Thanks.

You can have multiples table by defining different entity class for each table for example if we have two tables FactCategory and Facts, each FactCategory can have multiple facts.

Fact Category:

@Entity(tableName = "categories")
data class FactCategory(@PrimaryKey var id: String, var title: String)

Facts:

@Entity(tableName = "facts")
class Fact(
    @field:PrimaryKey val id: String,
    val title: String,
    val description: String?,
    val imageHref: String?,
    val catId: String
) 

In your database class, add all the required entity classes. You can not link two tables from different database.

Add the entities in your database class

@Database(entities = [::class, FactCategory::class], version = 1)

then in your DAO object, you can join two tables:

@Query("select f.id, f.title, c.title, f.description from categories c join  facts f on  c.id = f.catId")

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