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.
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.
| Concept | Django | Room |
|---|---|---|
| A table | class Item(models.Model) | @Entity data class Item |
| Primary key | Automatic id | @PrimaryKey(autoGenerate = true) val id: Long = 0 |
| Optional field | null=True, blank=True | A nullable type: val releaseYear: Int? |
| One-to-many | ForeignKey(ItemType) | An itemTypeId column plus @ForeignKey |
| Many-to-many | ManyToManyField(Tag) (the join table is hidden) | An explicit cross-reference entity you write yourself |
| Unique value | unique=True | An @Index(unique = true) |
| Creating the tables | makemigrations and migrate | Room 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.
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.
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.
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.
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.
| Relationship | On delete | Why |
|---|---|---|
| Item → ItemType | RESTRICT | Types are a fixed list; deleting one that is in use is a bug |
| Link → Item | CASCADE | Deleting an item should remove its tag links |
| Link → Tag | CASCADE | Deleting 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:
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.
@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,primaryKeysandIndex(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
idnon-default. WithautoGenerate = truethe property needs a default of 0 so you can create an item before it has been saved.
Challenges
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.
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.
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 solutionChapter 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
@Embeddedand@Relation(associateBy = Junction(...)for many-to-many) - Delete rules used here:
RESTRICTon Item → ItemType,CASCADEon both link foreign keys
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.
AppDatabase class, seeding the four item types on first launch, the repository, and light
Hilt wiring.