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

qkf9rpyu  于 12个月前  发布在  SQLite
关注(0)|答案(5)|浏览(126)

房间里有一个实体

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


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

bnl4lu3b

bnl4lu3b1#

不支持通过索引以外的方式对列进行普通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 = [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;
}

ehxuflar

ehxuflar2#

如果你想让一个列是唯一的,只需要写

@Entity(indices = [Index(value = ["name"], unique = true)])

字符串

2cmtqfgy

2cmtqfgy3#

对于单列Uniform

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

字符串
对于多列单列

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

dfty9e19

dfty9e194#

无法注解,所以我只是将其添加在这里。如果手动迁移您的Room DB以使用SQL语句添加索引,则您的索引名称必须符合表上的注解格式:

...
database.execSQL("CREATE UNIQUE INDEX index_tableName_columnName ON tableName (columnName)")
...

字符串
不确定索引名称可以有多长,因此不确定多列索引的外观。

7tofc5zh

7tofc5zh5#

还可以通过复合主键实现多列唯一性(实体由多列的组合唯一标识)。

@Entity(primaryKeys = ["firstName", "lastName"])
data class User(
    val firstName: String?,
    val lastName: String?
)

字符串
参见官方文档
请注意,在这种情况下,您不能使用自动生成的id增量SQLite doesn't support that

相关问题