Search code examples
android-room

Andorid room two primaryKeys , one autoGenerate


I want to have two primary keys, one should be autogenerated, I try do this:

@Entity(tableName = "object_to_group", primaryKeys = {"id" , "object_id"},)
public class ObjectsToGroup {

@ColumnInfo(name = "id",autoGenerate = true)
public long id;

but compilators show me error

when I do this:

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public long id;

a compilator show me error, what I should to do?


Solution

  • It is not possible with a composite primary key to add auto-increment. As an alternative, you can use unique indices. for example

    @Entity(tableName = "object_to_group", indices = {@Index(value = 
           {"object_id"}, unique = true)})
    public class ObjectsToGroup {
    
        @PrimaryKey(autoGenerate = true)
        private int id;
    
        @ColumnInfo(name = "object_id")
        private int object_id;
    }