Strangelove
Strangelove

Reputation: 791

Get two lists in one object from two tables using room

From my server I'm receiving object MyResponse, which contains two lists:

data class MyResponse(
    var field: List<Field>?,
    var group: List<Group>?
)

And then I'm saving it into two different tables, using ROOM

@Dao
interface MyDao {
    @Insert
    fun saveField(field: List<SavedField>)

    @Insert
    fun saveGroup(group: List<SavedGroup>)
}

SavedField

@Entity
data class SavedField (
        @ColumnInfo(name = "field")
        var field: String
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

SavedGroup

@Entity
data class SavedGroup(
        @ColumnInfo(name = "group")
        var group: String
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

But how to get MyResponse object again after writing data into database? Of course, I can use two @Query for each table, but I don't think that's the best solution.

Upvotes: 1

Views: 1074

Answers (1)

Jaykishan Sewak
Jaykishan Sewak

Reputation: 822

Check following code may be help you.

Solution 1

@Query("SELECT * FROM Field")
List<FieldAndGroup> findFieldAndGroup();

public class FieldAndGroup {
    @Embedded
    Field field;

    @Relation(parentColumn =  "Field.feild_id", entityColumn = "Group.id")
    //Relation returns a list
    //Even if we only want a single Bar object .. 
    List<Group> group;

    //Getter and setter...
}

Solution 2

@Query("SELECT Group.*, Field.* FROM Group INNER JOIN Field ON Field.grpId = Group.id")
List<GroupAndField> findAllGroupAndField();

public class GroupAndField {
    @Embedded
    Group group;

    @Embedded
    Field field;

    //Getter and setter...
}

Upvotes: 1

Related Questions