是否有必要在 Room 数据库中添加新 table 的迁移?

Is it neccessary to add migration if new table is added in Room database?

我有两个 tables,人已经存在(添加列 userid 作为 外键)

    @Entity(tableName = TABLE_NAME)
    data class Person(
    @PrimaryKey @ColumnInfo(name = CLIENT_ID) var id: Long,
    @ColumnInfo(name = USER_ID)var userId : Int = 1) : Parcelable {}

这是新加的class,有person的外键 class(用户 ID)

    @Entity(tableName = Profile.TABLE_NAME,
    foreignKeys = [ForeignKey(entity= Person::class,
    parentColumns = [(Person.USER_ID)],
    childColumns = [(Profile.USER_ID)],
    onDelete = ForeignKey.CASCADE)])
    @Parcelize
    data class Profile(@PrimaryKey(autoGenerate = true)
    var userId: Int,
    var name: String? = null):Parcelable{}

数据库中有两个 table。 现在,我是否需要编写迁移代码来创建新的 table?

如果您想将数据从以前的版本迁移到新版本 然后

Yes. You have to write the migration code.

如果您只想迁移架构而不迁移数据。 那就不用写迁移逻辑了。只需在房间生成器中添加 fallbackToDestructiveMigration()

示例:

Room.databaseBuilder(appContext, AppDatabase.class, AppDatabase.DATABASE_NAME)
            .fallbackToDestructiveMigration()
            .build();