Android Room数据库创建没有ID的实体对象
我的实体类别:
@Entity(tableName = "student")
data class Student(
@PrimaryKey(autoGenerate = true)
val id: Long,
val name: String,
val age: Int,
val gpa: Double,
val isSingle: Boolean
)
问题是,由于 id
是由 Room
数据库自动生成的-意味着我再没有将 id
放入的内容了构造函数无论如何都会被覆盖,并且由于它是构造函数中的参数之一,因此我每次都必须给 id
这样的代码:
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)
如何避免构成 id
,所以我可以像这样输入必要数据:
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)
如何避免填写ID
How can I avoid making up the id
只需将默认值设置为0(或为null)
Just set default value to 0 (or null)
@Entity(tableName = "student")
data class Student(
@PrimaryKey(autoGenerate = true)
val id: Long = 0, <-- default value (or use null)
id是由Room数据库自动生成的-意味着我将ID放到构造函数中的任何内容都不会被覆盖
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
并非如此.如果您明确设置 id
,则此 id
将在插入时使用.
Not really like that. If you set id
explicitly then this id
will be used on insert.