1

I have a data class contains id and code.

And I have a List contains codes only.

how to insert the codes into table without making up ids?

Actually I do not need the id column at all, but it seems Room requires a primary key, and codes cannot be primary key.

Room:

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

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

List and loop:

val codeList : List<String> = ...


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

1 Answers1

2
  1. Create a Dao like (or amend an existing Dao to include the @Insert as below)

:-

@Dao
interface RawDao {
    @Insert
    fun insertManyRaws(raws: List<Raw>): List<Long>
}
  1. Create the @Database as normal including abstract function to get the RawDao. e.g.

:-

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

You can then use something like :-

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
    }
}

Running the above results in :-

enter image description here

i.e. The 3 Raw's have been added to the database, as seen by using AS's Database Inspector

  • Note the dao.insertManyRaws call returns, as a List, the inserted id's (if any are -1 then that Raw was not inserted)
MikeT
  • 51,415
  • 16
  • 49
  • 68