With Insert Room datbase, I need insert two entity at one time.
@Transaction
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?): List<Long>
I read the documentation on the android developer site text This is allowed
However, when my project build one exception throw in build output:
Not sure how to handle insert method's return type.
I try change the type return like Long, Map, other but not complete. I hope everyone can help me
What you could do is have something along the lines of:-
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(baseChemical: BaseChemical): Long
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(langInfo: LanguageComplimentChemical): Long
@Transaction
@Query("")
/*suspend*/ fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?): List<Long> {
val rv1 = insert(baseChemical)
var rv2: Long = -1
if (langInfo != null) {
rv2 = insert(langInfo)
}
return listOf(rv1,rv2)
}
This when you want to insert the pair of entities you would use insertChemicalChemistry
@Query("")
is used to fool Room into considering the function should be run within a transaction. Without, unless things have changed, the function would not be run within a transaction.You could also have the freedom to insert the entities individually using the respective insert
function.
Consider the following demo:-
val bc = BaseChemical(null,"BC001","blah")
val lc = LanguageComplimentChemical(name = "LC001", etc = "more blah")
dao.insert(bc)
dao.insert(lc)
val result1 = dao.insertChemicalChemistry(bc,lc)
val result2 = dao.insertChemicalChemistry(bc,null)
val brkpnt = result1.get(0) + (result1.get(1) * 1024)
When run in debug mode then the result when the breakpoint is reached is:-
As can be seen:-
var rv2: Long = -1
to use another value if you wanted to differentiate between an ignored insert and a null LanguageComplimentChemical.