what do @Insert, @Update, @Delete, or @Query do?

Alan Ramirez
2 min readSep 22, 2020

--

These are all convenience annotations for the Room persistence library.

@Insert @Delete @Update

@Insert, @Update, and @Delete do just what the names imply. They do that type of database transaction when you pass in an object to the function they annotate. The only drawback is that if you want to do something more specific like deleting an object based on a certain field or updating on a certain field or retrieving items from the database then you would not be able to use any of these. You would have to use @Query().

onConflict

@Insert and @Update can have an OnConflictStrategy defined:

@Insert(onConflict = OnConflictStrategy.REPLACE)

@Update(onConflict = OnConflictStrategy.REPLACE)

the onConflict refers to a duplicate item, it triggers whenever you try to insert or update an object that has the same @PrimaryKey as an object of the same type that is already saved on the database. If you do write an onConflict strategy it will throw an error and crash your app.

REPLACE will overwrite the item in the database with the new item.

ABORT will stop the query and revert any changes made by that query transaction.

IGNORE will stop that query but continue executing everything else in that transaction.

More info here

Return types

@Insert can return either nothing or a Long that represents the row id of where the item was inserted or -1 no denote there was an error inserting such as when an item insertion triggers a conflict and the strategy is ABORT or IGNORE.

@Update can return either nothing or a Long that represents the row id of the item that was updated or -1 no denote there was no such item to be updated (no such item with that primary key).

@Delete can return either nothing or a Long that represents the row id of the item that was deleted or -1 no denote there was no such item to be deleted (no such item with that primary key).

@Query

The @Query annotation allows you to use SQL language in order to write more specific queries that give you more flexibility than those integrated into the library via the @Insert @Update @Delete annotations you can pass in your SQL strings into the annotation as such @Query(“SELECT FROM tablename”) which would return all objects saved on that table

--

--