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 ?
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
......
......
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With