Room — Entity Annotations

There are a selection of annotations available for use in Room Entity classes, here’s a brief explanation for some of them as I’ve been trying them out…

@Entity

@Entity
data class Person()

First of all, there’s the Entity annotation. Declaring the class as a Room Entity.

@Entity(tableName = "people")
data class Person()

Only a mad man would call a table person, surely it would be people. But the object should be person. Just specify the table name.

@Entity(indices = arrayOf(Index(value = "first_name", name = "name")))
data class Person()

If you want to index a column for faster searching of it, add indices (you may need to add an @ before Index in Java.


@PrimaryKey

@PrimaryKey(autoGenerate = true)
val id: Long

Declare a field the primary key for the database. Allow the database to auto increment using autoGenerate = true, take care of it yourself with autoGenerate = false.


@ColumnInfo

@ColumnInfo(name = "first_name")
val firstName: String = ""

Lets say that you like underscores in your SQL columns, but to put them in Java / Kotlin is not good. So with this annotation you can specify the SQL name and a nice Java / Kotlin name.


@Ignore

@Ignore
val bitmap: Bitmap

Pretty self explanatory. If we have something in our Pojo that doesn’t need to go into the database, just add this annotation.


@Embeded

@Entity
data class Person(
...
@Embedded
val address: Address
)

data class Address(val postcode: String,
val addressLine1: String)

This is very nice. We have a person, and that person has an address. We don’t really want to store all the address fields directly in the person. An Address object makes more sense. At the same time we want to be able to query parts of the address. If we embed an Address object, it will save as fields, but map back to an Address object.


@ForeignKey

@Entity
data class Person(
@PrimaryKey(autoGenerate = true)
val uid: Long,
val firstName: String = "",
val lastName: String = "",
val email: String = ""
)

@Entity(foreignKeys = arrayOf(ForeignKey(entity = Person::class,
parentColumns = arrayOf("uid"),
childColumns = arrayOf("ownerId"),
onDelete = ForeignKey.CASCADE)))
data class Pet(
@PrimaryKey(autoGenerate = true) val id: Long,
val ownerId: Long,
val name: String
)

Lets you specify foreign keys for entities, in this example a person has a pet, when the person is deleted, the pet is automatically deleted. There looks to be much more that can be done with Foreign Keys read here