【问题标题】:How to insert a List to a table with Dao Room in Android when there is a primarykey有主键时如何在Android中使用Dao Room将列表插入到表中
【发布时间】:2021-04-29 08:19:19
【问题描述】:

我有一个包含 id 和 code 的数据类。

我有一个只包含代码的列表。

如何在不补id的情况下将代码插入表格?

其实我根本不需要 id 列,但是好像 Room 需要主键,code 不能是主键。

房间:

@Entity(tableName = "raw_table")
data class Raw(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,

    @ColumnInfo(name = "code")
    var code: String = "",
    ...

列表和循环:

val codeList : List<String> = ...


for (code in codeList){
    // wrong here, I need the id, but I do not have ids.
    RawDao.insert(code)
}

【问题讨论】:

    标签: android insert android-room primary-key dao


    【解决方案1】:
    1. 创建一个类似的 Dao(或修改现有 Dao 以包含 @Insert,如下所示)

    :-

    @Dao
    interface RawDao {
        @Insert
        fun insertManyRaws(raws: List<Raw>): List<Long>
    }
    
    1. 照常创建@Database,包括获取RawDao 的抽象函数。例如

    :-

    @Database(entities = [Raw::class],version = 1)
    abstract class RawDatabase: RoomDatabase() {
        abstract fun getRawDao(): RawDao
    }
    

    然后你可以使用类似的东西:-

    class MainActivity : AppCompatActivity() {
    
        lateinit var db: RawDatabase
        lateinit var dao: RawDao
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            val rawList: List<Raw> = arrayListOf(Raw(0L,"Test1"),Raw(0L,"Test2"),Raw(0L,"etc...."))
            db = Room.databaseBuilder(this,RawDatabase::class.java,"raw.db")
                    .allowMainThreadQueries()
                    .build()
            dao = db.getRawDao();
            dao.insertManyRaws(rawList) //<<<<<<<<<< ADD All Raws at once
        }
    }
    

    运行上述结果:-

    即使用 AS 的 Database Inspector 可以看到 3 个 Raw 已添加到数据库中

    • 注意 dao.insertManyRaws 调用以列表形式返回插入的 id(如果有 -1 则表示未插入 Raw)

    【讨论】:

      猜你喜欢
      • 2018-06-19
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多