add unique constraint in room database to multiple column

前端 未结 3 422
灰色年华
灰色年华 2020-12-25 12:43

I have one entity in room

@Entity(foreignKeys ={
        @ForeignKey(entity = Label.class, parentColumns = \"_id\", childColumns = \"labelId\", onDelete = CA         


        
相关标签:
3条回答
  • 2020-12-25 13:13

    If you wonder to make a single column to be unique, only need to write

    @Entity(indices = [Index(value = ["name"], unique = true)])
    
    0 讨论(0)
  • 2020-12-25 13:13

    For a single column Uniqueness

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

    For Multiple column Uniqueness

    @Entity(indices = {@Index(value = {"first_name", "last_name"},unique = true)}) 
    
    0 讨论(0)
  • 2020-12-25 13:16

    A plain UNIQUE constraint on a column, other than via an index, is not supported.

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

    The Kotlin equivalent of the annotation is given below:

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

    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;
    }
    
    0 讨论(0)
提交回复
热议问题