Universally Unique IDs as a Primary Key in a Room Database

Paolo Montalto
3 min readApr 28, 2023

The default choice for primary key identifiers in a Room Database is usually an auto-generated Integer field, e.g. :

@PrimaryKey(autoGenerate = true) val id: Int

Integer IDs are plain and straightforward to implement but not so easy to handle when it comes to apps wich can run on multiple devices at the same time or when you have remotely stored data with all its consequences (e.g. coping with collisions is a literal hell)

In many cases like the foresaid ones having Universally Unique Identifiers maight come in handy.

Here follows a brief summary of how I managed to have UUIDs as primary keys in my Room Database based apps.

Let’s assume we have a simple Room entity we use to store our app’s users, like the one below:

@Entity
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val firstName: String,
val lastName: String
)

Room will auto-generate and auto-increment user IDs when you save it to the database.

Now let’s see how to achieve the same with UUIDs.

First of all we will need to convert our id to an UUID, like this:

@Entity
data class User(
@PrimaryKey val id: UUID,
val firstName: String…

--

--

Paolo Montalto

Android Engineer, freelance, mobile developer, software craftsman, guitar strummer, husband, father, humble.