Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial Entity Binding for Android Room

Tags:

android-room

Would like to confirm is it possible to bind an entity bean to partial columns of a table?

Example:

Table "A" has column id, col1, col2, col3, col4, col5, ... , col10

But I only need id, col1, col2, so I create a entity bean with fields id, col1, col2 and do binding for these fields only? I tried doing this but got:

Caused by: java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

Appreciate if anyone can verify is it possible to do the above binding using Room Persistence Library.

(Note: Why are there columns in my table which are not used in the mobile app. These tables schema are an exact copy of some tables in server side, hence some fields are used at server side webapp)

like image 482
user3109848 Avatar asked Mar 09 '23 17:03

user3109848


1 Answers

Returning subsets of columns

Most of the time, you need to get only a few fields of an entity. For example, your UI might display just a user's first name and last name, rather than every detail about the user. By fetching only the columns that appear in your app's UI, you save valuable resources, and your query completes more quickly.

https://developer.android.com/topic/libraries/architecture/room.html

You can define a model which does not have an @Entity annotation and use it at your select query.

// No @Entity annotation here !!!
public class NameTuple {
    @ColumnInfo(name="first_name")
    public String firstName;

    @ColumnInfo(name="last_name")
    public String lastName;
}

It isnt necessary to write another DAO (as the new class isnt an entity) - you can use the new Class as the return datatype from within any existing DAO.

// inside any existing DAO
    @Query("SELECT first_name, last_name FROM user")
    public List<NameTuple> loadFullName();
like image 177
Devrim Avatar answered Mar 20 '23 10:03

Devrim