将房间数据库中的唯一约束添加到多列

时间:2018-02-24 11:03:18

标签: android sqlite database-design android-room android-architecture-components

我在房间里有一个实体

@Entity(foreignKeys ={
        @ForeignKey(entity = Label.class, parentColumns = "_id", childColumns = "labelId", onDelete = CASCADE),
        @ForeignKey(entity = Task.class, parentColumns = "_id", childColumns = "taskId", onDelete = CASCADE)
})
public class LabelOfTask extends Data{
    @ColumnInfo(name = "labelId")
    private Integer labelId;
    @ColumnInfo(name = "taskId")
    private Integer taskId;
}

此实体的sql语法如下所示

CREATE TABLE `LabelOfTask` (
    `_id` INTEGER PRIMARY KEY AUTOINCREMENT,
     `labelId` INTEGER,
     `taskId` INTEGER,
     FOREIGN KEY(`labelId`) REFERENCES `Label`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE ,
     FOREIGN KEY(`taskId`) REFERENCES `Task`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE
 );

但是如果我想在下面的约束下追加到表的自动生成的sql架构,我需要在实体类中添加什么更改或注释

unique (labelId, taskId)

最终我想使用房间库在table(或房间的实体)中将labelId和taskId组合成唯一。

3 个答案:

答案 0 :(得分:14)

不支持列上的普通UNIQUE约束,而不是通过索引。

您可以通过将@Index注释的unique属性设置为true来强制实施此唯一性属性。以下代码示例(Java)可防止表包含两行,这些行包含firstName和lastName列的相同值集:

@Entity(indices = {@Index(value = {"first_name", "last_name"},
        unique = true)})
class User {
    @PrimaryKey
    public int id;

    @ColumnInfo(name = "first_name")
    public String firstName;

    @ColumnInfo(name = "last_name")
    public String lastName;

    @Ignore
    Bitmap picture;
}

注释的Kotlin等价如下:

@Entity(indices = arrayOf(Index(value = ["first_name", "last_name"], unique = true)))

在您的代码中,您可以执行以下更改以获得UNIQUE约束

@Entity(foreignKeys ={
        @ForeignKey(entity = Label.class, parentColumns = "_id", childColumns = "labelId", onDelete = CASCADE),
        @ForeignKey(entity = Task.class, parentColumns = "_id", childColumns = "taskId", onDelete = CASCADE)},
        indices = {@Index(value = {"labelId", "taskId"},
                unique = true)}
)
public class LabelOfTask extends Data{
    @ColumnInfo(name = "labelId")
    private Integer labelId;
    @ColumnInfo(name = "taskId")
    private Integer taskId;
}

答案 1 :(得分:1)

如果您想使单个列具有唯一性,只需编写

@Entity(indices = {@Index(value = "name", unique = true)})

答案 2 :(得分:0)

对于单列唯一性

@Entity(indices = {@Index(value = {"first_name"},unique = true)})

对于多列唯一性

@Entity(indices = {@Index(value = {"first_name", "last_name"},unique = true)})