Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rowid after Insert in Room

Tags:

android-room

I'm not sure about the value returned by an insert using the Room Persistence Library for Android, when the primary key is an autogenerated field.

Say you have a Room Entity like this:

@Entity()
public class Message {
    @PrimaryKey(autoGenerate = true)
    public long id;

    public String text;
}

and a Dao interface like this:

@Dao
public interface MessageDao {
    @Insert
    long insert(Message messages);

    @Update
    void update(Message... messages);
    }

I create a Message instance, and then I persist it like this:

Message message = new Message();
message.text = "Hello!"
long rowId = AppDatabase.getInstance(context).messageDao().insert(message);

Is the rowid value returned by the insert() always equal to the value assigned by Room to the primary key field "id", or they can differ?

In other words, is the "id" field an alias for the rowid column of the underlying SQLite table or not?

If they would be alias, I could store the rowid value in my "id" field, for future use (e.g. for update), this way:

message.id = rowId;
message.text = "Goodbye!"
AppDatabase.getInstance(context).messageDao().update(message);

If they are not alias, how can I do that?

like image 504
Cristiano Avatar asked Dec 08 '17 16:12

Cristiano


1 Answers

As the documentation (unfortunately not in the @Insert documentation) say:

If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.

To understand what rowId is follow this link: https://www.sqlite.org/rowidtable.html

The PRIMARY KEY of a rowid table (if there is one) is usually not the true primary key for the table, in the sense that it is not the unique key used by the underlying B-tree storage engine. The exception to this rule is when the rowid table declares an INTEGER PRIMARY KEY. In the exception, the INTEGER PRIMARY KEY becomes an alias for the rowid.

So... yes. rowId in your case IS an alias of your primary key. And YES you can store it for future use.

like image 109
Raymond Arteaga Avatar answered Nov 17 '22 18:11

Raymond Arteaga