CODE:
@Entity(tableName = "UserRepo", indices = @Index(value = "id", unique = true))
public class GitHubRepo {
@PrimaryKey(autoGenerate = true)
public int _id;
public int id;
public String name;
public String description;
@Embedded
public RepoOwner owner;
public GitHubRepo(int id, String name, String description, RepoOwner owner) {
this.id = id;
this.name = name;
this.description = description;
this.owner = owner;
}
public class RepoOwner {
@ColumnInfo(name = "user_id")
public int id;
public String login;
public RepoOwner(int id, String login) {
this.id = id;
this.login = login;
}
说明:
我有一个ROOM数据库,其中包含一个简单的表UserRepo
,该表包含三列_id, id, name
并使用" id"作为索引,以便有更快的查询。现在,我想使用@Embedded annotation
在此表中添加所有者信息。迁移代码如下:
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE UserRepo ADD COLUMN user_id INTEGER");
database.execSQL("ALTER TABLE UserRepo ADD COLUMN login TEXT");
}
};
在迁移过程中,出现了错误:
预期: TableInfo
{name='UserRepo', columns={name=Column{name='name', type='TEXT', notNull=false, primaryKeyPosition=0}, description=Column{name='description', type='TEXT', notNull=false, primaryKeyPosition=0}, _id=Column{name='_id', type='INTEGER', notNull=true, primaryKeyPosition=1}, id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=0}, login=Column{name='login', type='TEXT', notNull=false, primaryKeyPosition=0}, user_id=Column{name='user_id', type='INTEGER', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], **indices=[Index{name='index_UserRepo_id', unique=true, columns=[id]}]**}
发现: TableInfo
{name='UserRepo', columns={name=Column{name='name', type='TEXT', notNull=false, primaryKeyPosition=0}, description=Column{name='description', type='TEXT', notNull=false, primaryKeyPosition=0}, _id=Column{name='_id', type='INTEGER', notNull=true, primaryKeyPosition=1}, id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=0}, login=Column{name='login', type='TEXT', notNull=false, primaryKeyPosition=0}, user_id=Column{name='user_id', type='INTEGER', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], **indices=[]**}
似乎我在我的迁移工具中丢失了索引信息,我该如何解决这个问题?
另一个信息我可以通过从GitHubRepo实体中移除索引信息来解决此问题,但我不想这样做,因为我不想丢失指数的优势。
答案 0 :(得分:6)
最后,我通过在Migrate中为此表设置索引来修复此问题。代码为:
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE UserRepo ADD COLUMN user_id INTEGER");
database.execSQL("ALTER TABLE UserRepo ADD COLUMN login TEXT");
database.execSQL("CREATE UNIQUE INDEX index_UserRepo_id ON UserRepo (id)");
}
};
第三个SQL行是密钥。