How to write a one to (many pojos of two embedded entities) in Android Room

Viewed 551

How do I write a one to many relationship where the many is a pojo of two other embedded entities? There may be multiple Bs for one A but only one B for one A per DataList.

Here is a simplification of my code.

@Entity(tableName = "as")
public class A{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "a_id")
    private int mId;

    @ColumnInfo(name = "a_type")
    private String mType;

    //getters and setters
}

@Entity(tableName = "bs")
public class B{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "b_id")
    private int mId;

    @ColumnInfo(name = "b_type")
    private String mType;

    @ColumnInfo(name = "list_id")
    private int mListId;

    //getters and setters
}


@Entity(tableName = "data_lists")
public class DataList{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "data_list_id")
    private int mId;

    //getters and setters
}

public class AandB {
    @Embedded
    private A mA;

    @Embedded
    private B mB;

    //getters and setters
}

public  class DataListWithAandBs{
    @Embedded
    private DataList mDataList;

    @Relation(
            parentColumn = "data_list_id",
            entityColumn = "list_id")
    private List<AandB> mAandBList;

    //getters and setters
}

@Dao
public interface DataListWithAandBsDao {

    @Query("SELECT * FROM data_lists LEFT JOIN (SELECT * FROM as LEFT JOIN bs ON a_type = b_type) ON list_id = data_list_id")
    LiveData<List<DataListWithAandBs>> getDataListsWithAsandBs();
}

When I compile I receive the error: The class must be either @Entity or @DatabaseView. I don't want the list to be an entity though I want it to be a list of Pojos. Is this possible to do with room?

1 Answers

I believe you need to set the entity on the relation as follows:

public  class DataListWithAandBs{
    @Embedded
    private DataList mDataList;

    @Relation(
            parentColumn = "data_list_id",
            entityColumn = "list_id",
            entity = A.java
    )
    private List<AandB> mAandBList;

    //getters and setters
}

Because you want to fetch a relation from another table but want the return type to be something other than the table’s entity.

I did something similar in this project: https://github.com/emmaguy/room-playground/blob/master/app/src/main/java/com/monzo/room_playground/Database.kt#L33

Related