android room unique constraint (Kotlin)

Kotlin code:


Single column unique (e.g. id_key only).

@Entity(tableName = "user",indices = [(Index(value = ["id_key"], unique = true))])
data class User (

  @PrimaryKey(autoGenerate = true)
    var id: Int = 0
 
  @ColumnInfo(name = "id_key")
    var id_key: String = ""

    @ColumnInfo(name = "first_name")
    var first_name: String = ""

@ColumnInfo(name = "last_name")
    var last_name: String = ""
}


How to add unique constraint in room database to multiple column

Combine two columns to be unique (e.g. first_name and last_name).

@Entity(tableName = "user",indices = arrayOf(Index(value = ["first_name", "last_name"], unique = true)))
data class User (
.....
}


Multiple unique constaints.

@Entity(tableName = "user", indices = [Index(value = ["id_key"]),Index(value = ["first_name", "last_name"],unique = true)])
....
}

No comments:

Post a Comment

Popular Posts