Sobes.tech
Junior — Middle

Kuidas luua ühendus kahe tabeli vahel andmebaasis, mis kasutab Room?

sobes.tech AI

Vastus AI-lt

In Room, the relationship between two tables is established using foreign keys and annotations, as well as with special classes for data merging.

  1. Foreign Key — in the entity, you specify a field with the @ForeignKey annotation, which references the primary key of another table.

  2. Relations — to retrieve related data, POJO classes are created with @Relation annotations, which allow fetching nested objects from related tables.

Example of a "one-to-many" relationship:

@Entity
data class User(
    @PrimaryKey val userId: Int,
    val name: String
)

@Entity(
    foreignKeys = [ForeignKey(
        entity = User::class,
        parentColumns = ["userId"],
        childColumns = ["userOwnerId"],
        onDelete = ForeignKey.CASCADE
    )]
)
data class Book(
    @PrimaryKey val bookId: Int,
    val title: String,
    val userOwnerId: Int // foreign key
)

// Class to get user with their books
data class UserWithBooks(
    @Embedded val user: User,
    @Relation(
        parentColumn = "userId",
        entityColumn = "userOwnerId"
    )
    val books: List<Book>
)

This way, Room automatically links the tables and allows fetching related data through DAO.