Android Room迁移未正确处理

时间:2018-09-14 06:26:37

标签: android android-sqlite 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() {
}
}

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

缺少迁移中的createdAt字段

答案 1 :(得分:0)

似乎您正在尝试添加一列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表。如果要删除/创建,请确保首先使用新结构将数据复制到新表,将数据复制到新表,删除原始的Likes表,然后将新表重命名为Likes。参见示例here

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

相关问题