I am using Kotlin and Room for some basic operations. All the operations work fine but the updateAll
, it didn't update the database. The Dao like below:
@Dao
interface ItemListDao {
@Insert
fun insertAll(itemLists: List<ItemList>)
@Insert//(onConflict = OnConflictStrategy.IGNORE)
fun insert(itemLists: ItemList)
@Delete
fun delete(itemList: ItemList)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(itemList: ItemList)
@Transaction
fun upset(itemList: ItemList) {
try {
insert(itemList)
} catch (exception: SQLiteConstraintException) {
update(itemList)
}
}
@Transaction
fun updateAll(itemLists: List< ItemList>) {
itemLists.forEach {
upset(it)
}
}
}
@Entity
data class ItemList constructor(
@PrimaryKey val listId: String,
val displayName: String
}
The updateAll
function is used to check when the element in the list of itemLists existed, then update the element, if not then insert.
Also I think should I query to check if the itemList exist if not insert, if yes then update?
Not sure which one is better too.
EDIT: I used
@Update(onConflict = OnConflictStrategy.REPLACE)
on the udpate
method, and then in updateAll
, I call update
only, but actually can't pass the unit test.
EDIT My currect approach
@Transaction
fun updateAll(itemLists: List< ItemList>) {
itemLists.forEach {
val itemList = findItemList(it.listId)
if (itemList != null) {
update(it)
} else {
insert(it)
}
update(it)
}
}
Any help? Thanks a lot!