I have just found @PrimaryKey annotation in room. So If I want to make composite key so how can I do that?
-
12What does a composite primary key have to do with MVVM? – CommonsWare Nov 06 '17 at 11:19
-
Yes CommonsWare these both are independent. Thanks for pointing it out, I'll modify my question. – Lalit Kushwah Dec 01 '17 at 10:39
4 Answers
Make use of primaryKeys()
.
Android Developer Documentation for Room
states:
If PrimaryKey annotation is used on a Embeddedd field, all columns inherited from that embedded field becomes the composite primary key (including its grand children fields).
Example implementation in Java:
@Entity(primaryKeys = {"column1","column2","column3"})
public class DummyClass {
...
}
Example implementation in kotlin:
@Entity(primaryKeys = ["column1","column2","column3"])
class DummyClass {
...
}
Thanks Lalit Kushwah for the example.

- 601
- 6
- 14

- 8,197
- 7
- 35
- 50
-
8Thanks It worked, Here I am sharing the implementation in case if anyone requires: @Entity (primaryKeys = {"column1","column2"}) – Lalit Kushwah Dec 01 '17 at 10:37
-
1Is this the example of creating a composite primary key ?? – K Pradeep Kumar Reddy Jun 01 '20 at 05:58
-
Here is an example for Kotlin:
import android.arch.persistence.room.Entity
@Entity(primaryKeys= [ "first_name", "last_name" ] )
class User{
.......
}

- 334
- 3
- 10

- 7,794
- 4
- 48
- 44
-
2
-
1@WahibUlHaq https://stackoverflow.com/questions/46790830/how-to-make-primary-key-auto-increment-while-using-composite-primary-keys-in-roo that might answer your question – Prakash May 15 '18 at 18:43
-
2
-
33
This worked for me I'm using Kotlin 1.3, I think.
@Entity(tableName = "location_table", primaryKeys = ["lat", "lon"])
data class MyLocation(
// @PrimaryKey(autoGenerate = true) var id: Long?,
var lat: Double,
var lon: Double,
var dateTime: String,
var weatherDescription: String,
var temperature: Double
)

- 556
- 6
- 10
You can declare an entity on top of your existing entity class such as following
@Entity
(tableName = "Equipment_History", primaryKeys = {"EquipName","EquipFunctionalLocation"})
public class EquipmentHistory {
@ColumnInfo @NonNull
private String EquipFunctionalLocation;
@ColumnInfo @NonNull
private String EquipName;
//rest of the columns
}
In this way you can have the table name of your own choice and also can declare a composite primary key in room but make sure you add the @NonNull annotation alongside your @ColumnInfo annotation otherwise the code won't work, because room will give you a compile-time error otherwise as stated on the google developers website. Hope, this will help.

- 91
- 1
- 3