GreenDao insert,insertOrReplace,save

时间:2017-02-23 14:04:16

标签: android orm greendao

有人可以解释一下 GreenDao 库中方法insertinsertOrReplacesave之间的区别是什么?

我理解insert只插入insertOrReplace插入,如果不存在则更新/替换(如果存在)。

但是insertOrReplacesave之间的区别让人感到困惑?

由于

2 个答案:

答案 0 :(得分:7)

  • insert()将实体添加到表中,假设具有该密钥的实体不存在。如果存在,它将抛出异常

  • insertOrReplace()如果Key不存在,则将实体添加到表中,如果Key存在则替换。

  • save()添加没有Key into Table的Entity,如果表中存在Key和Entity则更新。如果实体具有密钥且表中不存在,则它将不执行任何操作。

答案 1 :(得分:1)

来自AbstractDao.java的{​​{3}}

"Save 'saves' an entity to the database: depending on the existence of the key 
property, it will be inserted (key is null) or updated (key is not null). 
This is similar to insertOrReplace, but may be more efficient, because if 
a key is present, it does not have to query if that key already exists."

通过查看save方法的代码,它在if方法中包含haskey语句,以确定是运行update还是{{1} }:

insert

if (hasKey(entity)) { update(entity); } else { insert(entity); } 执行实际的insertOrReplace sql语句。