javaandroiddatabaserx-javaandroid-room

Room request, one to many relathionship


Given

I have two classes, 'inspection' and 'items,' which have a one-to-many relationship, meaning one inspection can have many items, and each item is associated with a single inspection."

and I'm storing them as tables in a ROOM local database, they look like this:

Inspection

@Entity(tableName = "vehicle_inspection")
public class VehicleInspectionDB {

@PrimaryKey(autoGenerate = true)
private long inspectionDBId;
...
....

Item

@Entity(tableName = "inspection_item")
public class VehicleInspectionItemDB {


@PrimaryKey(autoGenerate = true)
private long itemDBId;
private long inspectionDBId;
...
....

I created this class in order to retrieve the inspections and the items associated:

Inspection with items class

public class InspectionAndItemsDB {
@Embedded
public VehicleInspectionDB inspection;
@Relation(
parentColumn = "inspectionDBId",
entityColumn = "itemDBId"
)
public List<VehicleInspectionItemDB> items;
}

and this Dao method:

DAO method

@Transaction
@Query("SELECT * FROM vehicle_inspection")
Flowable<List<InspectionAndItemsDB>> getInspectionAndItems();

The problem

when I use that method above get inspection and items I'm receiving only one child per parent it is only one item in the list per inspection instead of a list containing all the items associated with that inspection.

What's the issue? I've followed this tutorial by a google member: https://medium.com/androiddevelopers/database-relations-with-room-544ab95e4542

Thanks!


Solution

  • The problem is in your InspectionAndItemsDB class, in the @Relation annotation, you should change it to:

    public class InspectionAndItemsDB {
        @Embedded
        public VehicleInspectionDB inspection;
        
        @Relation(
            parentColumn = "inspectionDBId",  // Primary key (parent entity)
            entityColumn = "inspectionDBId"   // Foreign key (child entity)
        )
        public List<VehicleInspectionItemDB> items;
    }
    

    The value of entityColumn will be matched against the value defined in parentColumn(), so you should consider this. See: Relation Docs