我正在使用android.persistence.room来创建数据库。我有一个中间表,其中的行用其他两个表的PK标识,所以不需要id列(我没有使用游标)。我班里没有id字段,房间也没有抱怨。我添加了一个迁移,其中我创建了一个没有id列的新表;复制现有数据并重命名(sqlite中的典型drop column方法),仍然是id列。
@Entity(tableName = "recipe_ingredients",
foreignKeys = {
@ForeignKey(entity =
Recipe.class,
parentColumns = "id",
childColumns = "recipe",
onDelete = ForeignKey.CASCADE),
@ForeignKey(entity =
Ingredient.class,
parentColumns = "id",
childColumns = "ingredient",
onDelete = ForeignKey.RESTRICT)
},
primaryKeys = {"recipe", "ingredient"})
public class RecipeIngredient {
//region members
@ColumnInfo(name = "recipe")
private int mReceptId;
@ColumnInfo(name = "ingredient")
private int mIngredientId;
@Embedded
private Ingredient mIngredient;
@ColumnInfo(name = "amount")
private double amount;
@Ignore
private int mNumberOfRecipeIdChanges;
@Ignore
private int mNumberOfIngredientIdChanges;
//endregion
和我的迁移
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
// Create the new table
database.execSQL("CREATE TABLE recipe_ingredients_new " +
"(recipe INTEGER NOT NULL, ingredient INTEGER NOT NULL," +
" amount REAL NOT NULL," +
" PRIMARY KEY(recipe, ingredient), " +
"FOREIGN KEY(recipe) REFERENCES recipes(id)" +
" ON UPDATE NO ACTION ON DELETE CASCADE ," +
" FOREIGN KEY(ingredient) REFERENCES ingredients(id) " +
"ON UPDATE NO ACTION ON DELETE RESTRICT )" );
// Copy the data
database.execSQL(
"INSERT INTO recipe_ingredientes_new (recipe, "+
" ingredient, amount)" +
" SELECT recipe, ingredient, amount FROM
recipe_ingredients");
// Remove the old table
database.execSQL("DROP TABLE recipe_ingredients");
// Change the table name to the correct one
database.execSQL("ALTER TABLE recipe_ingredients_new RENAME TO
recipe_ingredients");
}
};