What does @PrimaryKey Do

Alan Ramirez
1 min readSep 20, 2020

--

@PrimaryKey annotation tells Room that only one object in that table can have a certain name.

In other words, if I have a Recipe type object and its name field is marked with @PrimaryKey and then I have an instance of object named “Spaghetti” saved in my Recipe table inside my database and I try to save another recipe instance also named “Spaghetti” into that same table, an exception will be thrown saying there is already an object with the same @PrimaryKey in my database.

You can also tell room to auto generate a primary key for you if it is of type Long or Integer by passing a true to the annotation @PrimaryKey(true) however these Id’s are generated when the object is inserted into the database thus the object will not have a value for this field until you save it and retrieve it from the database.

--

--