【问题标题】:Is it possible using String as PrimaryKey in Android Room是否可以在 Android Room 中使用 String 作为 PrimaryKey
【发布时间】:2018-05-18 20:29:03
【问题描述】:

我在我的 java 后端服务器中使用 uuid。所以我需要在房间 android 中使用该 uuid 来确保实体正确同步。 我知道Is it possible to apply primary key on the text fields in android database 和text as primarykey in android。我想创造这样的东西

@Entity(tableName = CrewColumns.TABLE_NAME)
@TypeConverters(BigDecimalConverter::class)
@JsonIgnoreProperties(ignoreUnknown = true)
class Crew() {
    constructor (uuid: String) : this() {
        this.uuid = uuid;
    }

    /**
     * The unique ID of the item.
     */
    @PrimaryKey
    @ColumnInfo(name = CrewColumns.UUID)
    var uuid: String = ""
    @ColumnInfo(name = CrewColumns.NAME)
    var name: String = ""
}

Room(DAO 等)会有问题吗?谢谢。

【问题讨论】:

  • 您当然可以使用字符串作为主键。您在尝试时遇到了什么具体问题?
  • @CommonsWare 目前没有。

标签: java android kotlin android-room


【解决方案1】:

是的,您可以将String 用作@PrimaryKey。

此外,我还建议使用 Kotlin 的 data class 来简化您的实体。例如:

@Entity
data class Crew(@PrimaryKey val uuid: String, val name: String) {
    // Put any functions or other members not initialized by the constructor here
}

【讨论】:

  • @juanmeanwhile kotlin 怎么样?我们是否也必须注释 NonNull 吗?
  • @mochadwi 不需要,因为该语言已经有一种方法可以指示字符串不可为空。
  • 如果执行插入并且主键是String类型,返回类型是什么,它也可以是String类型吗?喜欢,在下面显示? @Insert(onConflict = OnConflictStrategy.REPLACE) Single 插入(船员);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多