android 如何更改房间数据库的主键?

ulydmbyx  于 2022-12-16  发布在  Android
关注(0)|答案(2)|浏览(290)

更改主键需要更新数据库版本。是否可以使用Room中的Migration类将主键从一个字段更改为另一个字段?如果不能,如何更改主键?以下是Entity的片段。

@Entity(tableName = "weather")
public class Weather {
    @PrimaryKey
    @NonNull
    @ColumnInfo(name = "id")
    private final String id;

    @NonNull
    @ColumnInfo(name = "city")
    private final String city;

我想从id切换到city

zfycwa2u

zfycwa2u1#

您必须创建一个新表,将数据从旧表复制到新表,删除旧表,然后将新表重命名为原始名称。
示例:将主键playlist_entry.id重命名为playlist_entry.entry_id

private val MIGRATION_8_9 = object : Migration(8, 9) {
    // rename playlist_entry.id to playlist_entry.entry_id
    override fun migrate(database: SupportSQLiteDatabase) {
        // create new temp table
        database.execSQL("CREATE TABLE IF NOT EXISTS playlist_entry_new (entry_id INTEGER NOT NULL, playlist_id INTEGER NOT NULL, tab_id INTEGER NOT NULL, next_entry_id INTEGER, prev_entry_id INTEGER, date_added INTEGER NOT NULL, transpose INTEGER NOT NULL, PRIMARY KEY(entry_id))")

        // copy data from old table to new
        database.execSQL("INSERT INTO playlist_entry_new (entry_id, playlist_id, tab_id, next_entry_id, prev_entry_id, date_added, transpose) SELECT id, playlist_id, tab_id, next_entry_id, prev_entry_id, date_added, transpose FROM playlist_entry")

        // delete old playlist_entry table
        database.execSQL("DROP TABLE playlist_entry")

        // rename new table to playlist_entry
        database.execSQL("ALTER TABLE playlist_entry_new RENAME TO playlist_entry")
    }
}

字符串

omtl5h9j

omtl5h9j2#

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
        .addMigrations(MIGRATION_1_2).build();

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE weather CHANGE id city VARCHAR(22) NOT NULL;");
    }
};

相关问题