我能否在Room中将非主键字段设置为自动生成的值?

10

我有一张具有复合主键的表格。我能否将其中一个字段设置为自动生成的?

场景: 我有一张名为teacher table的表格,包含字段teacherId、name、gender、role、department、grade,并且它具有由role、department和grade组成的复合主键。如何将teacherid设置为自动生成的?


请点击此处查看:https://dev59.com/5FYN5IYBdhLWcg3w27Uv#46804610 - Hussnain Haidar
@Rakki,你试过这个答案了吗? - ankuranurag2
我试过了,它有效。 - Rakki s
1个回答

7

如果您阅读此答案,您会发现我们无法在复合主键中使用自动递增属性。因此,解决方法是使用“索引”和“唯一约束”概念。将roledepttgrade列设置为indices,并将unique约束设置为true。这将确保这三个值的组合始终是唯一的(就像主键)。然后在实体中将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
    ......
    ......
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接