4

I have a Many to Many relationship set up on my Room database denoted by the following diagram: enter image description here

I want to add extra field to "CrossRef" table. My question is how do I go about having DateWithSteaks get this "isCompleted" variable from "CrossRef" table?

@Entity
public class Steak{

    @PrimaryKey(autoGenerate = true)
    public int id;

    public String title;
}


@Entity
public class Date {
    @PrimaryKey
    public long date;

    public Date() {
        date = new LocalDate().toDate().getTime();
    }
}


@Entity(primaryKeys = {"date", "id"})
public class DateSteakCrossRef {
    public long date;
    public int id;
    public boolean isCompleted;
}


public class DateWithSteaks {
    @Embedded Date date;

    @Relation(
            parentColumn = "date",
            entityColumn = "id",
            associateBy = @Junction(DateSteakCrossRef.class)
    )

    public List<Steak> steaks;
}

1 Answers1

3

I had the same problem, it was impossible to fix in an intuitive way.

The closest to a solution I got was to add the cross-ref entity (in your sample DateSteakCrossRef) as a one-to-many relationship inside the result object (DateWithSteaks).

Is not the best thing, but at least you can get all the data in a single transaction.

Something like this:

public class DateWithSteaks {
    @Embedded Date date;
    @Relation(
            parentColumn = "date",
            entityColumn = "id",
            associateBy = @Junction(DateSteakCrossRef.class)
    )
    public List<Steak> steaks;
    @Relation(
        parentColumn = "id", // id of your Date clase
        entityColumn = "id"  // id of your DateSteakCrossRef class
    )
    public List<DateSteakCrossRef> steaksRefs;
}

Then, in your code, you will need to match the steaks and steaksRefs to map to another object with the data you need.

francosang
  • 353
  • 3
  • 15