Search code examples
javaandroiddatabasesqliteandroid-room

How to change primary key of Room database?


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.


Solution

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