Can i make non-primary key field as autogenerated value in room
Asked Answered
U

1

11

I have table with composite primary key. Can I make one of the filed as auto generated.

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 ?

Uncleanly answered 13/2, 2019 at 10:15 Comment(3)
check here. https://mcmap.net/q/100538/-how-to-make-primary-key-auto-increment-while-using-composite-primary-keys-in-room-persistent-libraryMassage
@Rakki you tried the answer?Kissiah
ya i tried its workedUncleanly
K
7

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
    ......
    ......
}
Kissiah answered 14/2, 2019 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.