我正在创建一个实体(房间持久性库)类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自增字段?


当前回答

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

其他回答

添加@PrimaryKey(autoGenerate = true)

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

    //type-1
    public User(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    //type-2
    public User(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

}

存储数据时

 //type-1
 db.userDao().InsertAll(new User(sName,sPhone)); 

 //type-2
 db.userDao().InsertAll(new User(0,sName,sPhone)); 

1型 如果您不传递value为主键,默认情况下它将为0或 null。

2型

在创建对象(我的case user对象)时为id置空或零

如果字段类型为long或int(或其TypeConverter将其转换为long或int), Insert方法在插入项时将0视为未设置。

如果字段的类型是Integer或Long (Object)(或者它的TypeConverter将其转换为Integer或Long), Insert方法在插入项时将null视为未设置。

用下面的代码注释你的Entity类。

在Java中:

@PrimaryKey(autoGenerate = true)
private int id;

在芬兰湾的科特林:

@PrimaryKey(autoGenerate = true)
var id: Int

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

在下面的例子中,当您创建一个新用户时,将参数传递给构造函数。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;
    }

}
@Entity(tableName = "user")
data class User(

@PrimaryKey(autoGenerate = true)  var id: Int?,
       var name: String,
       var dob: String,
       var address: String,
       var gender: String
)
{
    constructor():this(null,
        "","","","")
}

你可以像这样添加@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()
}