I have just found @PrimaryKey annotation in room. So If I want to make composite key so how can I do that?
A composite key in SQL can be defined as a combination of multiple columns, and these columns are used to identify all the rows that are involved uniquely. Even though a single column can't identify any row uniquely, a combination of over one column can uniquely identify any record.
Composite Key in SQL. 1 1. Primary Key Declaration. SQL Syntax declaration for PRIMARY KEY Constraint defines as below: Code: Create table table_name ( Col1 data_type_1 NOT ... 2 2. Composite Key Declaration. 3 1. ALTER Composite Key. 4 2. DROP Composite Key.
Here individually the specified columns will not be unique, the combination of the columns gets the uniqueness and able to fetch data from the table. A composite key is derived from a combination of two or more columns that combined make a unique column, which individually does not provide uniqueness.
We can use all foreign keys in the composite keys. Data types specified in the composite key can be different. It is derived in the form of below pattern:
Composite is NOT NULL and UNIQUE Foreign key will be included in the composite key After identification of the composite key, we mention it as a primary key in the table. Which will be used for the identification of the rows from the table.
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.
Here is an example for Kotlin:
import android.arch.persistence.room.Entity
@Entity(primaryKeys= [ "first_name", "last_name" ] )
class User{
.......
}
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
)
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