我正在创建一个实体(房间持久性库)类Food,在那里我想使foodId作为自增量。

@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()
}

如何设置foodId自增字段?


当前回答

例如,如果你有一个用户实体,你想存储,字段(姓,姓,电子邮件),你想自动生成id,你这样做。

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

然后,Room将自动生成并自动增加id字段。

其他回答

你可以像这样添加@PrimaryKey(autoGenerate = true):

@Entity
data class Food(
        var foodName: String, 
        var foodDesc: String, 
        var protein: Double, 
        var carbs: Double, 
        var fat: Double
){
    @PrimaryKey(autoGenerate = true)
    var foodId: Int = 0 // or foodId: Int? = null
    var calories: Double = 0.toDouble()
}

例如,如果你有一个用户实体,你想存储,字段(姓,姓,电子邮件),你想自动生成id,你这样做。

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

然后,Room将自动生成并自动增加id字段。

这对我来说很管用:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

请注意,id放在最后,以避免在将实体插入Room之前创建实体时必须使用命名参数。一旦它被添加到room,在更新实体时使用id。

在这么多答案之后,这是令人难以置信的,但我最后做的有点不同。我不喜欢主键为空,我想把它作为第一个参数插入时不定义它,它也不应该是var。

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

在下面的例子中,当您创建一个新用户时,将参数传递给构造函数。Room将自动生成id。所有用户对象id在id setter中已经设置为int默认值,所以不要调用setId

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    @ColumnInfo(name = "phone")
    private String phone;

   
    public User(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public void setId(int id){
        this.id = id;
    }

}