room

作者: 王家匀匀 | 来源:发表于2020-11-17 21:24 被阅读0次

1. @Entity 中,不需要保存的字段,不能写到构造方法中。

正确写法:写到类实体中,并且@Ignore;

2. @Query 查询的数据,需要使用列表接收。

可以使用 List,不能使用ArrayList 。会报错:

[A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution](https://prodevsblog.com/questions/42362/a-failure-occurred-while-executing-org-jetbrains-kotlin-gradle-internal-kaptexec/)

3.迁移数据库表:

遇到的业务场景是 将一个字段非空改为允许为null.
如果是MySql 就简单了:使用 MODIFY 或者CHANGE

ALTER TABLE table_name MODIFY column_name datatype
但是:mySql alert table 只支持 add/rename
所以只能4步走:
step1:创建一个新的符合要求字段的新表table_new;
step2:将旧表table中的数据拷贝到新表table_new中;

INSERT INTO table_new(var1,var2...) SELECT var1,var2... from table

step3:删除旧表table;
step4:将新表table_new重命名为table,升级完毕。

以上这种方法,还适应:

  1. 加、减字段;
  2. 修改字段数据结构(比如int 改为String);
  3. 修改表约束。

这种方法的缺点:
copy旧表数据时,如果有几十个变量,这...真的是体力活。

参考了:
http://noharry.cc/2018/07/23/Room%E7%89%88%E6%9C%AC%E8%BF%81%E7%A7%BB%E9%81%87%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98/
以下是同事找的官方例子:

image.png

单纯的alert table 适用于 add column 加字段。

4. 本地数据库 实现列表元素 已读、未读功能:

step1.获取数据列表;
如果数据库完全为空,整个网络列表数据保存到数据库中;
如果数据库列表有元素,根据网络获取的列表进行遍历.存在于数据库中的元素,获取对应状态并赋值到网络列表数据中;不存在于数据库中的元素,保存到数据库中;
step2:点击条目;
数据库中查询该条目id,如果有,update表中read字段为true。没有则不操作。

5. @Embedded (适用于 类嵌套)

类A嵌套类B,且A加了@Entity.
这时候只需要在A中B的对象加注解@Embedded。(B不需要加@Entity)

   public class Coordinates {
       double latitude;
       double longitude;
   }
   public class Address {
       String street;
       @Embedded
       Coordinates coordinates;
   }

官方文档:
https://developer.android.com/reference/android/arch/persistence/room/Embedded

5. @Dao

@Dao
interface MyDao {

    /**
     * 插入数据
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertMyBean(info: MyBean)

    /**
     * 更新数据
     */
    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun updateMyBean(info: MyBean)

    /**
     * 查询 id 和类型一致的数组
     */
    @Query("SELECT * from MyTable where type=:type and id=:id")
    fun queryBeanById(type: Int, id: Long): List<MyBean>

    /**
     * 获取 experienceType 类型的数据列表
     */
    @Query("SELECT * from MyTable where type=:type")
    fun queryBeanByType(type: Int): List<MyBean>

}

相关文章

网友评论

      本文标题:room

      本文链接:https://www.haomeiwen.com/subject/ljdfiktx.html