Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 ?

like image 771
Rakki s Avatar asked Feb 13 '19 10:02

Rakki s


1 Answers

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
    ......
    ......
}
like image 123
ankuranurag2 Avatar answered Nov 13 '22 18:11

ankuranurag2