How to change primary key of Room database?

Bernard Koh

Changing my Primary key required me to update my database version. Is there any way to change my primary key from one field to another using Migration class in Room? If not how do I change my primary key? The following is a snippet of my Entity.

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

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

I would like to switch from id to city.

Addisalem
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;");
    }
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to add primary key in room database?

Is it possible to change the value of a primary key of some Room database?

How to ignore primary key when I insert room database entity

Migrate Room database with Autoincrement Primary Key

How to auto increment primary key in Room?

Android Room: How to know if a primary key exists?

Room persistent database - how to insert list of items into DB when it has no primary key related to table

Error with making Enum as primary key at Room database Library

How to change single primary key to composite primary key with EF Core

How to make primary key as autoincrement for Room Persistence lib

How to migrate from table without primary key using room?

Android Room - Autogenerate Primary Key

Primary key is not increase room android

How can I change current value for identity type primary key column in table in PostgreSQL database?

how to get all the primary key from a database

Alembic: How to change the length of a Primary Key field?

How to change the length of a Primary Key field in Alembic?

How to change Primary Key of entity in MagicalRecord?

Room composite Primary Key link to Foreign Key

How to make Primary key Auto increment while using Composite Primary keys in Room persistent library?

change primary key values

How to change primary key of a postgres database table from bill no to bill no and year part of purchase date column(it is oif type date)?

Room doesn't autogenerate Primary Key

Primary key not autogenerated using Room's Entity

Android room composite primary key, sort order

Android Room Composit Primary key issue

Primary key from parent class using Room?

AutoIncrement primary key in subclass of Room model

android, room: is autogenerated primary key always monotonic