Data Model

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 2 ยท Entities, Relations and Indices

Chapter 1 left you with an empty project and a "My Catalogue" screen. This chapter writes the shape of the data: four Kotlin classes that Room will turn into four SQLite tables. There is no database object, no queries and no screen yet; those come in Chapter 3. Getting the model right first matters because every later chapter reads or writes these classes, and changing a table after the app is installed means writing a migration.

What was run, and what was not
Nothing in this chapter was run or compiled, as in Chapter 1: this machine has no Android Studio. The Room pattern for a many-to-many relation was checked against Google's documentation (see the boxes at the end); the rest is written from general knowledge of Room and Kotlin. Room's annotation processor checks entities when you build, so your first build is the real test: read its error messages, they are usually precise.

From Django Models to Room Entities

If you built a web catalogue, you already made these decisions once. An Android entity is a Kotlin data class marked @Entity; Room creates one table per entity and one column per property.

ConceptDjangoRoom
A tableclass Item(models.Model)@Entity data class Item
Primary keyAutomatic id@PrimaryKey(autoGenerate = true) val id: Long = 0
Optional fieldnull=True, blank=TrueA nullable type: val releaseYear: Int?
One-to-manyForeignKey(ItemType)An itemTypeId column plus @ForeignKey
Many-to-manyManyToManyField(Tag) (the join table is hidden)An explicit cross-reference entity you write yourself
Unique valueunique=TrueAn @Index(unique = true)
Creating the tablesmakemigrations and migrateRoom generates them from the entities when the database is built (Chapter 3)

The one real difference is the many-to-many row. Django hides the join table; Room makes you write it, and that explicit class is the most important thing to understand in this chapter.

The Four Entities

Create a file for each entity in the data package you planned in Chapter 1 (right-click it, New > Kotlin Class/File). Start with the two simple ones.

ItemType

A fixed lookup list (Book, CD, DVD, Blu-ray) that Chapter 3 seeds on first launch. Its name must be unique, so it gets a unique index.

package com.example.catalogue.data import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "item_type", indices = [Index(value = ["name"], unique = true)] ) data class ItemType( @PrimaryKey(autoGenerate = true) val id: Long = 0, val name: String )

Tag

A tag is just a name, but the spec says "Web Development" and "web development" must not both exist. A unique index alone would allow both, because SQLite compares text case-sensitively by default. The usual fix is to give the column a case-insensitive collation, so the unique index compares names without regard to case.

package com.example.catalogue.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "tag", indices = [Index(value = ["name"], unique = true)] ) data class Tag( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(collate = ColumnInfo.NOCASE) val name: String )

Note that NOCASE in SQLite folds only the 26 basic English letters, so it handles "Sci-Fi" and "sci-fi" but not accented letters such as "ร‰". For a personal catalogue that is an acceptable limit; Chapter 7 also trims and normalises names before saving, so the database rule is a safety net rather than the only defence.

Item

The main entity. It points at its type with a foreign key, and everything else is plain data. Two choices are worth explaining. The creation time is a Long (milliseconds since 1970), which Room stores natively and which needs no converter. And the optional year is Int?, which Room stores as a nullable column.

package com.example.catalogue.data import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "item", foreignKeys = [ ForeignKey( entity = ItemType::class, parentColumns = ["id"], childColumns = ["itemTypeId"], onDelete = ForeignKey.RESTRICT ) ], indices = [ Index(value = ["itemTypeId"]), Index(value = ["title"]) ] ) data class Item( @PrimaryKey(autoGenerate = true) val id: Long = 0, val title: String, val creator: String = "", val formatDetail: String = "", val releaseYear: Int? = null, val notes: String = "", val createdAt: Long = System.currentTimeMillis(), val itemTypeId: Long )

onDelete = RESTRICT means SQLite refuses to delete an item type while items still use it. That is the right rule here, since types are a fixed list the user never deletes; it turns a bug in your own code into an error instead of silent data loss. The two indices serve later chapters: itemTypeId makes the list's type filter fast (and Room's documentation recommends indexing a foreign-key child column), and title helps the search screen.

ItemTagCrossRef

A tag can be on many items and an item can have many tags, so neither table can hold the link. A third table does: one row per (item, tag) pair. Per Google's guidance, this cross-reference entity has a composite primary key made of both ids, so the same tag cannot be attached to the same item twice.

package com.example.catalogue.data import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index @Entity( tableName = "item_tag", primaryKeys = ["itemId", "tagId"], foreignKeys = [ ForeignKey( entity = Item::class, parentColumns = ["id"], childColumns = ["itemId"], onDelete = ForeignKey.CASCADE ), ForeignKey( entity = Tag::class, parentColumns = ["id"], childColumns = ["tagId"], onDelete = ForeignKey.CASCADE ) ], indices = [Index(value = ["tagId"])] ) data class ItemTagCrossRef( val itemId: Long, val tagId: Long )

Here CASCADE is deliberate: deleting an item removes its links (but never the tags themselves), and deleting a tag removes it from every item. The composite key already gives an index that starts with itemId, so only tagId needs its own index, for the "which items have this tag?" query in Chapter 8.

RelationshipOn deleteWhy
Item → ItemTypeRESTRICTTypes are a fixed list; deleting one that is in use is a bug
Link → ItemCASCADEDeleting an item should remove its tag links
Link → TagCASCADEDeleting a tag should detach it everywhere

Loading an Item with Its Type and Tags

The list and detail screens want an item together with its type name and its tags, not four separate lookups. Room models that with a plain (non-entity) class that embeds the item and declares its relations. The many-to-many one names the cross-reference through Junction:

package com.example.catalogue.data import androidx.room.Embedded import androidx.room.Junction import androidx.room.Relation data class ItemWithDetails( @Embedded val item: Item, @Relation( parentColumn = "itemTypeId", entityColumn = "id" ) val type: ItemType, @Relation( parentColumn = "id", entityColumn = "id", associateBy = Junction( value = ItemTagCrossRef::class, parentColumn = "itemId", entityColumn = "tagId" ) ) val tags: List<Tag> )

Read it as three sentences. The item is embedded. Its type is the ItemType whose id equals the item's itemTypeId. Its tags are the Tags reached by going through ItemTagCrossRef, from this item's id to each link's itemId, then from tagId to the tag's id. Chapter 3 writes the DAO query that returns this class; the DAO method needs @Transaction because Room runs several queries to fill the relations.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 2, SwiftData models are classes marked @Model, and the relationship is a property such as var tags: [Tag]: there is no cross-reference class to write. Android's data model is longer because Room is a thin layer over SQL tables, while SwiftData hides the join table, as Django does. The fields, types and rules (unique tag names, no deleting a type in use) are identical.

Common Mistakes

  • Forgetting the foreign-key index. Room warns at build time when a child column of a foreign key has no index. Add the index rather than suppressing the warning.
  • Mismatched column names. childColumns, primaryKeys and Index(value = ...) use the column names (the property names unless you change them with @ColumnInfo), spelled exactly.
  • Storing a tag list inside the item. A comma-separated string works until the first rename. A link table is the correct, queryable design.
  • Making id non-default. With autoGenerate = true the property needs a default of 0 so you can create an item before it has been saved.

Challenges

Exercise 1

Create the five files (ItemType.kt, Tag.kt, Item.kt, ItemTagCrossRef.kt, ItemWithDetails.kt) in the data package. You cannot build a database yet, so check them by building the project (Build > Make Project) only if Room is already in your Gradle files; otherwise just confirm the files have no red underlines once you add the Room dependency named in Chapter 3. Write down what each import is for.

๐Ÿ“„ View solution
Exercise 2

The spec says a duplicate warning compares title and creator, case-insensitively (Chapter 9). Decide whether to enforce that with a unique index on Item or to do it in code, and justify the choice. Remember that the spec calls it a warning, never a block.

๐Ÿ“„ View solution
Exercise 3

Sketch, on paper or in a text file, the rows of all four tables after you add a book "Dune" tagged sci-fi and classic, and a DVD "Alien" tagged sci-fi. Then say which rows disappear if you delete the tag sci-fi, and which if you delete "Dune".

๐Ÿ“„ View solution

Chapter 2 Quick Reference

  • Entity: @Entity data class; one table per entity, one column per property; nullable property = nullable column
  • Key: @PrimaryKey(autoGenerate = true) val id: Long = 0; composite key: @Entity(primaryKeys = ["a", "b"])
  • Foreign key: ForeignKey(entity, parentColumns, childColumns, onDelete); index the child column
  • Unique value: Index(value = ["name"], unique = true); case-insensitive text: @ColumnInfo(collate = ColumnInfo.NOCASE)
  • Many-to-many: an explicit cross-reference entity with a composite key and two foreign keys
  • Reading relations: a non-entity class with @Embedded and @Relation (associateBy = Junction(...) for many-to-many)
  • Delete rules used here: RESTRICT on Item → ItemType, CASCADE on both link foreign keys
Not Yet Verified
Checked (one web search on 2026-11-19): that Google's documentation models many-to-many with a third cross-reference class using a composite primaryKeys and indices; that the reading class uses @Embedded plus @Relation with associateBy = Junction(...); that those queries are run in a @Transaction; and that the ForeignKey reference says the parent column must be a primary key or unique, with an index on the child table recommended.
Not checked, from general knowledge: that Google's own example does not add foreignKeys to the cross-reference (the search did not show one; I added them as consistent with the ForeignKey reference); the RESTRICT and CASCADE behaviour described; ColumnInfo.NOCASE and its English-letters-only limit; the exact Junction parameter names; Room's build-time warning about unindexed foreign keys; and every import and every line of code, none of which was compiled.
Sources for This Chapter
Search results (2026-11-19): Android Developers, Define and query many-to-many relationships; Android Developers, Choose relationship types between objects; Junction API reference; ForeignKey API reference. Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 3 adds the Room dependencies, the DAOs, the AppDatabase class, seeding the four item types on first launch, the repository, and light Hilt wiring.