如何在 Room 中制作组合键

How to make composite key in Room

我刚刚在房间里找到@PrimaryKey 注释。那么,如果我想制作复合键,我该怎么做呢?

利用primaryKeys().

Android Developer Documentation 对于 Room 状态:

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).

Java中的示例实现:

@Entity(primaryKeys = {"column1","column2","column3"})
public class DummyClass {
    ...
}

kotlin 中的示例实现:

@Entity(primaryKeys = ["column1","column2","column3"])
class DummyClass {
    ...
}

感谢 Lalit Kushwah 举例。

这里有一个 Kotlin 的例子:

import android.arch.persistence.room.Entity

@Entity(primaryKeys= [ "first_name", "last_name" ] )
class User{
    .......
}

这对我有用,我想我正在使用 Kotlin 1.3。

@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
    )

您可以在现有实体之上声明一个实体class,例如以下

@Entity
 (tableName = "Equipment_History", primaryKeys = {"EquipName","EquipFunctionalLocation"})
public class EquipmentHistory {

    @ColumnInfo @NonNull
    private String EquipFunctionalLocation;
    @ColumnInfo @NonNull
    private String EquipName;
//rest of the columns 

}

通过这种方式,您可以拥有自己选择的 table 名称,也可以在 room 中声明复合主键,但请确保您在 @ColumnInfo 注释旁边添加了 @NonNull 注释,否则代码将失败' 工作,因为 room 会给你一个编译时错误,否则如 google 开发者网站上所述。 希望,这会有所帮助。