Android Room Kotlin:多实体插入方法返回值报错求助
解决Room插入两个实体时返回类型报错的问题
问题原因
你当前的写法中,@Insert直接接收一个非空实体和一个可空实体,Room无法正确推断返回值的映射逻辑——因为如果第二个参数为null,对应的插入操作不会执行,返回的List<Long>长度不确定,导致Room生成代码时抛出Not sure how to handle insert method's return type异常。
同时,Room的@Insert方法仅支持返回Long(单个插入)、List<Long>(多个非空实体插入)或Unit/Void,Map这类类型本身就不被支持。
解决方案
通过@Transaction包裹两个独立的@Insert方法,分别处理每个实体,再手动组合返回结果:
@Dao interface ChemicalDao { // 单独插入BaseChemical,返回对应的rowId @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertBaseChemical(base: BaseChemical): Long // 单独插入LanguageComplimentChemical,返回对应的rowId @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertLangChemical(lang: LanguageComplimentChemical): Long // 在事务中执行两个插入操作,组合结果返回 @Transaction suspend fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?): List<Long> { val resultList = mutableListOf<Long>() // 插入第一个实体,添加结果 resultList.add(insertBaseChemical(baseChemical)) // 如果第二个实体非空,插入并添加结果 langInfo?.let { resultList.add(insertLangChemical(it)) } return resultList } }
补充说明
如果不需要返回具体的rowId,也可以将返回类型改为Unit,简化逻辑:
@Transaction suspend fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?) { insertBaseChemical(baseChemical) langInfo?.let { insertLangChemical(it) } }
内容的提问来源于stack exchange,提问作者VIL
相关产品推荐
相关产品推荐

