码:
@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;
}
Run Code Online (Sandbox Code Playgroud)
说明:我有一个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");
}
};
Run Code Online (Sandbox Code Playgroud)
迁移期间,出现以下错误:
预期: 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]}]**}
Run Code Online (Sandbox Code Playgroud)
找到: 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=[]**}
Run Code Online (Sandbox Code Playgroud)
似乎我在迁移工具中丢失了索引信息,该如何解决?
另一个信息我可以通过从GitHubRepo实体中删除索引信息来解决此问题,但是我不想这样做,因为我不想失去索引的优势。
最后,我通过在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)");
}
};
Run Code Online (Sandbox Code Playgroud)
SQL的第三行是关键。
| 归档时间: |
|
| 查看次数: |
1721 次 |
| 最近记录: |