Android Studio ROOM数据库:无法自动生成主键

rjee0c15  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(226)

这是我代码,我认为它100%正确

@Serializable
@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    var userID: Int = 1,
    var fullName: String = "Missing",
    var email: String = "Missing",
    var password: String = "Missing",
    var phone: Long = -1,
    var profileImage: String = "Missing",
    var userType: Int = -1,
) {

    constructor(
        userID: Int = 1
    ) : this(
        fullName = "Missing",
        email = "Missing",
        password = "Missing",
        phone = -1,
        profileImage = "Missing",
        userType = -1,

        )
}

还有,为什么tableName & autoGenerate没有显示为蓝色

因为代码以前对我有效,但现在不知道为什么不起作用了

7gcisfzg

7gcisfzg1#

删除您在构造函数中设置默认id,让它由数据库实现(当它为您自动生成id时)

@PrimaryKey(autoGenerate = true)
val userID: Int, // no = 1

同时删除第二个构造函数,并将所有变量保留为final(因此是val,而不是var
编辑:示例

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val userID: Int,
    val fullName: String = "Missing",
    val email: String = "Missing",
    val password: String = "Missing",
    val phone: Long = -1,
    val profileImage: String = "Missing",
    val userType: Int = -1,
)
nvbavucw

nvbavucw2#

我发现了问题
userID: Int = 0编号1

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    var userID: Int = 0,
    var fullName: String = "Missing",
    var email: String = "Missing",
    var password: String = "Missing",
    var phone: Long = -1,
    var profileImage: String = "Missing",
    var userType: Int = -1,
) {

    constructor(
        userID: Int
    ) : this(
        userID,
        fullName = "Missing",
        email = "Missing",
        password = "Missing",
        phone = -1,
        profileImage = "Missing",
        userType = -1,
        )
}

相关问题