Home > Software engineering >  Correct approach to query from one (only) table using association table in Android ROOM
Correct approach to query from one (only) table using association table in Android ROOM

Time:12-01

I have been searching the stackoverflow community on how to approach the situation below. There is a table called APPOINTMENTS which two or more APPOINTMENTS may be LINKED to each other. For instance:

ID START END
1 10:00am 12:00pm
2 12:00pm 01:00pm
3 04:00pm 04:30pm

AppointmentModel.kt

So, APOINTMENTS 1 and 2 may be linked to each other, meaning actually they are some sort of the same event divided into two APOINTMENTS (like work and lunch hours).

I have created an association table to keep those rows linked in a many to many relation:

ID LINKED_ID
1 2
2 1

AppointmentJoinRef.kt

I would use those associations in a way that the deletion of ID 1 should cascade to ID 2 (vice-versa).

My POJO looks like this right now:

data class ApointmentsPOJO(
   @Embedded var Appointment: AppointmentModel,

   @Relation(
       entity = AppointmentModel::class,
       parentColumn = "ID",
       entityColumn = "ID",
       associateBy = Junction(AppointmentJoinRef::class)
       var linkedAppointments: List<AppointmentModel>

From this code, all I can fetch from table is a list containing repetitions of the "parent" Appointment. I am not able to fetch the linked Appointment, and I am afraid it may be not possible from this approach. I have also tried to mess it up changing parentColumn and entityColumn both in the Relation and in the Junction parameters.

My question is: What is the correct approach?

CodePudding user response:

You need to specify the columns used within the association table by using the parentColumn (ID) and entityColumn(LINKED_ID) parameters of the Junction.

So something like:-

@Relation(
    entity = AppointmentModel::class,
    parentColumn = "ID",
    entityColumn = "ID",
    associateBy = Junction(AppointmentJoinRef::class, parentColumn="ID",entityColumn="LINKED_ID)
    var linkedAppointments: List<AppointmentModel>

CodePudding user response:

Well, I am not sure if this is the best answer, but this is how I solved this issue for now.

I have written another POJO

data class LinkedAppointmentPojo (
    @Embedded val model: AppointmentJoinRef,

    @Relation(
        parentColumn = "LINKED_ID",
        entityColumn = "ID"
    )
    val linkedAppointments: List<Appointment>
)

So the AppointmentPojo is now:

data class ApointmentsPOJO(
   @Embedded var Appointment: AppointmentModel,

   @Relation(
       entity = AppointmentModel::class,
       parentColumn = "ID",
       entityColumn = "ID"
   )
       var linkedAppointments: List<LinkedAppointmentPojo>
)

I can find the list of appointment linked to another appointment by chaining appointmentPojo.linkedAppointments[index].linkedAppointments and it feels too long. Still it is a solution and I am now unblocked.

  • Related