我在当前的 Android 应用程序中使用 Room 作为我的本地数据库。
我有一个一对多的父子表关系,我想在其中插入多个父行,将自动生成的 ID 作为列表接收回来,然后为每个父 ID 插入多个子项。
我可以依靠 Room 以与传递给 INSERT 语句的父行相同的顺序返回自动生成的父 ID 吗?
我一次收到 200 个父行,这意味着我不想插入单个父行,因为这种方法会降低性能。
有什么方法可以插入多个 Parent -> Children one-2-many 行并让子行自动接收父自动生成的 id?
有什么方法可以插入多个 Parent -> Children one-2-many 行并让子行自动接收父自动生成的 id?
我怀疑存在这样的方法。尽管您可以考虑下一个解决方法(当然它有一些缺点,但您可以考虑它是否适合您的特定情况) - 在插入之前显式地在您的和实体中获得最大值id
和 set id
s 。假设您要插入 200 个项目。你得到最大电流- 1000。然后你在你的第一个父/子对中设置's - 1001,在第二个 - 1002 等等。有了它,您可以在 single 中插入父级和子级列表。Parent
Child
id
id
Insert
我可以依靠 Room 以与传递给 INSERT 语句的父行相同的顺序返回自动生成的父 ID 吗?
你可以。看看 Room 的方法insertAndReturnIdsList
,当你插入实体列表时会调用它:
// THIS METHOD IS CALLED WITHIN TRANSACTION WHEN YOU CALL YOUR INSERT-DAO-METHOD
public final List<Long> insertAndReturnIdsList(Collection<? extends T> entities) {
final SupportSQLiteStatement stmt = acquire();
try {
final List<Long> result = new ArrayList<>(entities.size());
int index = 0;
for (T entity : entities) { <-- LOOPING LIST OF INSERTED ENTITIES
bind(stmt, entity);
result.add(index, stmt.executeInsert()); <-- INSERT ONE-BY-ONE IN ONE TRANSACTION
index++; <-- INDEX OF RESULT LIST MATCHES INDEX OF ENTITIES LIST
}
return result;
} finally {
release(stmt);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句