我可以将非主键字段设置为房间中的自动生成的值吗? [英] Can i make non-primary key field as autogenerated value in room
问题描述
我有带有复合主键的表.我可以将其中之一设为自动生成吗?
I have table with composite primary key. Can I make one of the filed as auto generated.
场景:我有一个 teacher table
,其中包含字段techerId,姓名,性别,角色,部门,职等,并且它具有由角色,部门和职等组成的复合主ID.如何使Teacherid为自动生成的?
Secenario :
I have a teacher table
containing the fields techerId, name, gender, role, department, grade and it has composite primary id which consist of role, department and grade. How to make teacherid as auto-generated ?
推荐答案
如果您通过此答案,您将发现复合主键中没有自动递增属性.因此,解决方法是使用索引
和唯一约束
的概念.在 indices
中设置 roles
, deptt
, grade
列,并设置 unique
约束为 true
.这将确保这三个值对始终是唯一的(例如primaryKey).然后在实体中将 techerId
添加为 Primarykey
(autoGenerate = true).您的 entity
类类似于:
If you go through THIS ANSWER, you will find that we can't have auto increment property in Composite Primary keys. So, the workaround would be to use concept of indexing
and unique constraint
. Make the role
,deptt
,grade
columns as you indices
and set the unique
constraint as true
. This will ensure that the pair of these three values are always unique(like primaryKey). Then add the techerId
as Primarykey
(autoGenerate = true) in the entity. Your entity
class would look something like:
@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
......
......
}
这篇关于我可以将非主键字段设置为房间中的自动生成的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!