Comment on page
9.4 Entities
When you use the Room persistence library to store your app's data, you define entities to represent the objects that you want to store. Each entity corresponds to a table in the associated Room database, and each instance of an entity represents a row of data in the corresponding table.
You define each Room entity as a class that is annotated with
@Entity
. A Room entity includes fields for each column in the corresponding table in the database, including one or more columns that comprise the primary key (Each Room entity must define a primary key that uniquely identifies each row in the corresponding database table. The most straightforward way of doing this is to annotate a single column with @PrimaryKey)
.The following code is an example of a simple entity that defines a GroceryItem table:
@Entity // Can use @Entity(tableName = "<CUSTOM_NAME>") to change the table name.
data class GroceryItem(@PrimaryKey val item: String,
val brand: String,
@ColumnInfo(name = "cost") val number: Int // Can use @ColumnInfo to define your column name differently.
)
Here, each item in our grocery list has 3 fields: a name, a brand, and the number needed.
Note: To persist a field, Room must have access to it. You can make sure Room has access to a field either by making it public or by providing getter and setter methods for it.
Last modified 1yr ago