首页 > 解决方案 > Android Room 迁移未正确处理

问题描述

我已经编写了 Android Room 迁移,但不知何故它不能正确处理它。

这是错误:

    Expected:
TableInfo{name='Likes', columns={creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, createdAt=Column{name='createdAt', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
 Found:
TableInfo{name='Likes', columns={dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}

这是迁移脚本:

database.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
                       + " timestamp TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))");

这是模型类:

@Entity(tableName = "Likes")
public class LikeDbModel {

@PrimaryKey private int dbId;
private String id;
private String creatorId;
private String messageId;
private String timestamp;
private String createdAt;

public LikeDbModel() {
}
}

任何人都可以帮忙吗?

标签: androidandroid-sqliteandroid-room

解决方案


您似乎正在尝试添加 createdAt 列。当您创建数据库时,将 .addMigrations(MIGRATION_1_2) 行添加到数据库的创建中,我认为您已经完成了。

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        YourDatabase.class, "your_database.db")
                        .addMigrations(
                                MIGRATION_1_2
                        )
                        .build();

然后通过首先删除表然后创建它或使用alter table 语句来正确实施迁移。

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase db) {
           //Either
           db.execSQL("drop table Likes"); //if existing table
           db.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
                   + " timestamp TEXT, createdAt TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))")

            //or
            db.execSQL("alter table add createdAt TEXT");

    }
};

您得到的错误是因为房间正在将您的实体与数据库中的现有表进行比较。您还可以将迁移语句包装在 try/catch SQLiteException 中,以查看什么是有效的。

如果您不想丢失表中的数据,请改用 alter table。如果要删除/创建,请确保首先使用新结构将数据复制到新表,将数据复制到新表,删除原始 Likes 表并将新表重命名为 Likes。在此处查看示例

房间文档:https ://developer.android.com/training/data-storage/room/migrating-db-versions


推荐阅读