Search code examples
androidandroid-room

Room : making an "one to one to many" relation


I am working with room persistence library in android. I know to make an "one to many" relations, but I would like to know if it's possible to make an "one to one to many" relation. Here is a simplified schema of my database (there is more columns in each table) : db schema

Here is the data class that links "Appointment" and "Diagnostic" :

data class AppointmentWithDiagnostic(
    @Embedded
    val appointment: Appointment,

    @Relation(
        parentColumn = "idDossier",
        entityColumn = "appointmentId"
    )
    val diagnostic: Diagnostic,
)

And the data class that links Diagnostic with description and survey :

data class DiagnosticWithDescriptionAndSurvey(
    @Embedded
    val diagnostic: Diagnostic,

    @Relation(
        parentColumn = "id",
        entityColumn = "diagnosticId"
    )
    val description: Description,

    @Relation(
        parentColumn = "id",
        entityColumn = "diagnosticId"
    )
    val survey: Survey,
)

I thought about making a request that links directly all the tables or linking directly Survey and Description directly to Appointment. If it's not possible to make an "one to one to many" relation, I guess I would go with one of those solutions.


Solution

  • If I understand correctly, you could have:-

    data class AppointmentWithDiagnostic(
        @Embedded
        val appointment: Appointment,
    
        @Relation(
            entity = Diagnostic::class, //<<<<<<<<< IMPORTANT 
            parentColumn = "idDossier",
            entityColumn = "appointmentId"
        )
        val diagnosticWithDescriptionAndSurvey: DiagnosticWithDescriptionAndSurvey,
    )
    
    • Note in-principle code not compiled or run (now compiled)

    • if you don't specify the entity (IMPORTANT) then the compile will fail as the class defaults to the class of the field and that is not a table (@Entity).

      • e.g. error: The class must be either @Entity or @DatabaseView. public final class DiagnosticWithDescriptionAndSurvey {