Android 房间 - 自动生成主键
Android Room - Autogenerate Primary Key
我遇到了一个问题,我找不到关于 Android 的 Room 和自动生成主键的任何文档。
我有一个实体 class 看起来有点像这样:
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private int id;
public void setId(int id) {
this.id = id;
}
}
当我手动设置 id 时,这工作正常,但当我不设置主键时,我收到关于主键为 null 的错误。查看自动生成的文件,我在任何地方都看不到它会自动递增主键。
所以我想我的问题是:你能用 setter 自动生成私有成员的主键吗?还是我需要在 setter 中手动自动生成我的密钥?
好的,所以这段代码不会生成 id 成员,因为成员为 null 我必须将它设置为 Integer 对象,在这种情况下,当成员等于 null 时,它会自动生成一个新的 id ,或者,我需要在初始化将执行相同操作的对象时将其设置为等于 0。
我已将其设置为整数,完美解决了我的问题。
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
}
我遇到了一个问题,我找不到关于 Android 的 Room 和自动生成主键的任何文档。
我有一个实体 class 看起来有点像这样:
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private int id;
public void setId(int id) {
this.id = id;
}
}
当我手动设置 id 时,这工作正常,但当我不设置主键时,我收到关于主键为 null 的错误。查看自动生成的文件,我在任何地方都看不到它会自动递增主键。
所以我想我的问题是:你能用 setter 自动生成私有成员的主键吗?还是我需要在 setter 中手动自动生成我的密钥?
好的,所以这段代码不会生成 id 成员,因为成员为 null 我必须将它设置为 Integer 对象,在这种情况下,当成员等于 null 时,它会自动生成一个新的 id ,或者,我需要在初始化将执行相同操作的对象时将其设置为等于 0。
我已将其设置为整数,完美解决了我的问题。
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
}