【问题标题】:Can i make non-primary key field as autogenerated value in room我可以将非主键字段作为房间中的自动生成值吗
【发布时间】:2019-02-13 10:15:02
【问题描述】:
我有一个带有复合主键的表。我可以将其中一个文件设为自动生成吗?
场景:
我有一个 teacher table 包含字段 techerId、姓名、性别、角色、部门、等级,它具有由角色、部门和等级组成的复合主 ID。如何让teacherid自动生成?
【问题讨论】:
标签:
android
sqlite
android-room
android-database
【解决方案1】:
如果你通过THIS ANSWER,你会发现我们不能在复合主键中拥有自增属性。因此,解决方法是使用indexing 和unique constraint 的概念。将role,deptt,grade 列设置为indices,并将unique 约束设置为true。这将确保这三个值的对始终是唯一的(如primaryKey)。然后将techerId 添加为实体中的Primarykey(autoGenerate = true)。你的 entity 类看起来像:
@Entity(tableName = "teacher",indices = arrayOf(Index(value = ["role","department","grade"],unique = true)))
public class Teacher{
@PrimaryKey(autoGenerate = true)
int teacher_id;
@ColumnInfo(name = "name")
String teacher_name;
//Rest of the fields
......
......
}