In this section, you’ll walk through how to create entities for your Room database.
You’ll make a few changes in your NoteEntity data class to make it an entity. Head over to the data/local package and open the NoteEntity.kt file. Add the @Entity annotation to the class and the @PrimaryKey annotation to the id property. Your updated NoteEntity class should look like this:
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable
@Entity(tableName = "notes")
@Serializable
data class NoteEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val title: String,
val description: String,
val timestamp: Long,
val priority: String,
val noteLocation: String
)
You use the @Entity annotation to define the class as an entity. You have the tableName parameter to define your table name. You define your primary key using the @PrimaryKey annotation. Additionally, you specify the autoGenerate parameter. This parameter specifies that the primary key is created every time you insert a new row in the table.
Next, still in the data/local package, open the DevScribeDatabase class and add your newly created entity to the database. Your updated DevScribeDatabase class should look like this:
@Database(entities = [NoteEntity::class], version = 1)
abstract class DevScribeDatabase: RoomDatabase() {
}
Inside the @Database annotation, you define the entities that belong to the database. In this case, you only have one entity, NoteEntity.
With the changes you’ve made, your app can now compile and run. The table will be created in the database when you run the app for the first time. It will be created with the name you specified in the @Entity annotation. The first-time run will also create the columns you defined in the NoteEntity class. But the database won’t have any data yet. You’ll need to create the DAO first. You’ll learn how to do that in the next section.