In the Room Persistence Library, to make a primary key auto-increment, we use the annotation @PrimaryKey(autoGenerate = true)
. This tells Room that the field should automatically increase its value each time a new record is inserted into the database.
Example:
java
CopyEdit
@Entitypublic class Student { @PrimaryKey(autoGenerate = true) public int id; public String name; public int age; }
In the example above, the id
field is the primary key, and autoGenerate = true
ensures that Room will auto-increment it for each new Student
entry.
Conclusion:
To make a primary key auto-increment in Room, use @PrimaryKey(autoGenerate = true)
.