Android\'s Room persistence library graciously includes the @Insert and @Update annotations that work for objects or collections. I however have a use case (push notificatio
I could not find a SQLite query that would insert or update without causing unwanted changes to my foreign key, so instead I opted to insert first, ignoring conflicts if they occurred, and updating immediately afterwards, again ignoring conflicts.
The insert and update methods are protected so external classes see and use the upsert method only. Keep in mind that this isn't a true upsert as if any of the MyEntity POJOS have null fields, they will overwrite what may currently be in the database. This is not a caveat for me, but it may be for your application.
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract void insert(List entities);
@Update(onConflict = OnConflictStrategy.IGNORE)
protected abstract void update(List entities);
@Transaction
public void upsert(List entities) {
insert(models);
update(models);
}