Room Entity: Your Database Table as a Kotlin Class

A Room Entity is a data class that maps to a database table; each object is a row, each property a column. Use it to define your local SQLite schema in Android. The footgun: forgetting the `@PrimaryKey` annotation, which is required for Room to manage.
WHY IT EXISTS Manually writing SQL to create database tables and map query results to objects is tedious and error-prone. Room Entities were created to automate this process, providing a compile-time checked, object-oriented layer over an app's local SQLite database.
THE MENTAL MODEL A Room Entity is a blueprint for a database table, written as a simple Kotlin or Java data class. You define the table's structure—its columns and their types—using class properties, and Room handles the SQL translation. An instance of an entity class, like User(id=1, name="Alex"), represents a single row in the users table.
HOW IT WORKS You create a data class and annotate it with @Entity. At compile time, Room's annotation processor inspects this class. It uses the class properties to determine the column names and types for the database table. You must designate one property as the @PrimaryKey so Room can uniquely identify each row. Other annotations like @ColumnInfo can customize column names, and @Ignore can prevent a property from being saved to the database. Room uses this information to generate the necessary CREATE TABLE SQL statement.
WHEN TO USE IT Use an entity for every table you need in your app's local SQLite database. This is the standard way to define your data schema when using the Room library for local persistence, such as caching user data, storing settings, or saving content for offline access.
WHEN NOT TO USE IT Don't use an entity for data that doesn't need to be persisted in a structured, relational database. For simple key-value pairs, use Android's Jetpack DataStore or SharedPreferences. An entity is also not the right tool for representing temporary, in-memory state that doesn't need to survive an app restart.
ONE CANONICAL EXAMPLE To create a users table, you define a class like this: @Entity(tableName = "users") data class User( @PrimaryKey(autoGenerate = true) val id: Int = 0, @ColumnInfo(name = "first_name") val firstName: String?, @ColumnInfo(name = "last_name") val lastName: String? ) This class tells Room to create a table named "users" with three columns: an auto-incrementing integer id, a text column first_name, and a text column last_name.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.