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

编程入门 行业动态 更新时间:2024-10-27 22:20:43
本文介绍了将房间数据库中的唯一约束添加到多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我房间里有一个实体

@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语法如下

sql syntax of this entity is as below

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 模式,我需要在实体类中添加什么更改或注释

but what change or annotation I need to add in entity class if I want to append below constraint to the auto generated sql schema of the table

unique (labelId, taskId)

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

Ultimately I want to make combination of labelId and taskId unique in a table(or entity of room) using room library.

推荐答案

不支持对列的普通 UNIQUE 约束(通过索引除外).

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

You can enforce this uniqueness property by setting the unique property of an @Index annotation to true. The following code sample (Java) prevents a table from having two rows that contain the same set of values for the firstName and lastName columns:

@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 等价的注解如下:

The Kotlin equivalent of the annotation is given below:

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

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

In your code you can do the following changes to have UNIQUE constraints

@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; }

更多推荐

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

本文发布于:2023-06-13 09:28:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库中   房间   到多列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!