Step #2: Defining an Entity

In Room, an entity is a class that is our in-memory representation of a SQLite table. Instances of the entity class represent rows in that table.

So, we need an entity to create a SQLite table for our to-do items.

Which means… we need another Kotlin class!

Right-click over the com.commonsware.todo.repo package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in ToDoEntity and choose “Class” as the kind. Press Enter or Return to create the class, giving you:

package com.commonsware.todo.repo

class ToDoEntity {
}

Then, replace that stub implementation with this:

package com.commonsware.todo.repo

import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import java.time.Instant
import java.util.*

@Entity(tableName = "todos", indices = [Index(value = ["id"])])
data class ToDoEntity(
  val description: String,
  @PrimaryKey
  val id: String = UUID.randomUUID().toString(),
  val notes: String = "",
  val createdOn: Instant = Instant.now(),
  val isCompleted: Boolean = false
)

This class has the same properties as ToDoModel. You might wonder why we did not just use ToDoModel. Mostly, that is for realism: there is no guarantee that your entities will have a 1:1 relationship with models. Room puts restrictions on how entities can be constructed, particularly when it comes to relationships with other entities. Things that you might do in model objects (e.g., a category object holding a collection of item objects) wind up having to be implemented significantly differently using Room entities. Those details will get hidden by your repositories. A repository exists in part to convert specialized forms of your data (Room entities, Web service responses, etc.) into the model objects that your UI is set up to use.

What makes ToDoEntity an entity is the @Entity annotation at the top. There, we can provide metadata about the table that we want to have created. Here, we specify that we want the underlying table name to be todos, as opposed to the default, which is the same as the class name (ToDoEntity).

Room knows that the id property is our primary key because we gave it the @PrimaryKey annotation. Room wants us to declare some primary key, typically via that @PrimaryKey annotation. We also have an index on our id column, courtesy of the @Index nested annotation inside of the @Entity annotation.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.