我可以在房间中将非主键字段设置为自动生成的值

问题描述 投票:0回答:1

我有复合主键的表。我可以将其中一个提交为自动生成。

场景:我有一个teacher table,包含字段techerId,名称,性别,角色,部门,等级,它有复合主要ID,包括角色,部门和等级。如何使teacherid成为自动生成的?

android sqlite android-room android-database
1个回答
3
投票

如果你通过THIS ANSWER,你会发现我们在Composite主键中没有自动增量属性。因此,解决方法是使用indexingunique constraint的概念。像role一样制作depttgradeindices列,并将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
    ......
    ......
}
© www.soinside.com 2019 - 2024. All rights reserved.