Room 使用遇到的问题

Room 使用遇到的问题

  1. 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

  1. 设置字段为非空约束

    在字段上面添加@NonNull 注解

    @NonNull
    @ColumnInfo(name = "reader_id")
    public String reader_id;
    

参考:Room 使用之如何为字段设置非空约束

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值