My entity class:
@Entity(tableName = "student")
data class Student(
@PrimaryKey(autoGenerate = true)
val id: Long,
val name: String,
val age: Int,
val gpa: Double,
val isSingle: Boolean
)
The problem is, since the id
is auto-generated by the Room
database - means no matther what I put for the id
into the constructor it will be overridden anyway, and because it is one of the parameter in the constructor, I have to give the id
every time like this:
val student = Student(0L, "Sam", 27, 3.5, true)
How can I avoid making up the id
so I can just put in the neccessary data like this:
val student = Student("Sam", 27, 3.5, true)
In Kotlin, this means that title can never be null. To fix this, you just need to change the Entity class a bit, and allow the fields to be Nullable . val type: Int, val url: String?
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. The following code is an example of a simple entity that defines a User table with columns for ID, first name, and last name: Kotlin Java.
How do you indicate that a class represents an entity to store in a Room database? Make the class extend DatabaseEntity . Annotate the class with @Entity . Annotate the class with @Database .
Don't place the id in the constructor:
@Entity(tableName = "student")
data class Student(
val name: String,
val age: Int,
val gpa: Double,
val isSingle: Boolean
) {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
}
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