Room 使用遇到的问题
- Migration didn’t properly handle
Migration 升级数据库时,更新表结构时,SQL语句
AlTER TABLE User ADD COLUMN sync_state integer
运行时,报错,当已经存在的数据表跟新的数据表不同时会抛出此异常,修改SQL语句为
AlTER TABLE User ADD COLUMN sync_state integer NOT NULL DEFAULT 1
参考:Migration didn’t properly handle
-
设置字段为非空约束
在字段上面添加@NonNull 注解
@NonNull @ColumnInfo(name = "reader_id") public String reader_id;
3.column references a foreign key but it is not part of an index
user_id column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column.
user_id列引用一个外键,但它不是索引的一部分。这可能会在父表被修改时触发全表扫描,因此强烈建议您创建一个覆盖该列的索引
@Entity(foreignKeys = @ForeignKey(entity = User.class,
parentColumns = "reader_id",
childColumns = "user_id",onDelete = ForeignKey.CASCADE),indices = {@Index(value = "id",unique = true),@Index(value = "user_id")})
public class Book {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public int id;
/**
*
*/
@NonNull
@ColumnInfo(name = "user_id")
public String user_id;
}
@Entity(indices = {@Index(value = {"reader_id"},unique = true)})
public class User {
@PrimaryKey(autoGenerate = true)
public int uid;
@ColumnInfo(name = "user_name")
public String userName;
@NonNull
@ColumnInfo(name = "reader_id")
public String reader_id;
}
Book表的user_id是User表的外键,在book表上的user_id添加index 索引
参考:
https://stackoverflow.com/questions/44480761/android-room-compile-time-warning-about-column-in-foreign-key-not-part-of-an-ind
pile-time-warning-about-column-in-foreign-key-not-part-of-an-ind