I am creating an Entity (Room Persistence Library) class Food, where I want to make foodId
as autoincrement.
@Entity class Food(var foodName: String, var foodDesc: String, var protein: Double, var carbs: Double, var fat: Double) { @PrimaryKey var foodId: Int = 0 var calories: Double = 0.toDouble() }
How can I set foodId
an autoincrement field?
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.
implements Annotation. android.arch.persistence.room.PrimaryKey. Marks a field in an Entity as the primary key. If you would like to define a composite primary key, you should use primaryKeys() method. Each Entity must declare a primary key unless one of its super classes declares a primary key.
A Room entity includes fields for each column in the corresponding table in the database, including one or more columns that comprise the primary key.
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With