I’m using Room Database to build my Android app and want to gather some suggestion from community.
Let’s say I have the Note
Entity and the Label
Entity. Both of them has the n – n relationship with the other.
So when I want to return a List of Labels with its Notes or List of Notes with its Labels I have to write the custom query in DAO and define the data class to store the returned value.
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int = 0,
@ColumnInfo(name = "title")
val title: String,
@ColumnInfo(name = "content")
val content: String,
@ColumnInfo(name = "created_at")
val createAt: Long,
@ColumnInfo(name = "updated_at")
val updatedAt: Long
)
@Entity(
tableName = "labels",
indices = [androidx.room.Index(value = ["name"], unique = true)]
)
data class Label(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int = 0,
@ColumnInfo(name = "name")
val name: String
)
@Entity(tableName = "note_labels",
indices = [androidx.room.Index(value = ["note_id", "label_id"], unique = true)])
data class NoteLabel(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo(name = "note_id")
val noteId: Int,
@ColumnInfo(name = "label_id")
val labelId: Int
)
My question is Should I use the annotation @Relation or manually write the JOIN query in DAO? I though both of them are using to return the Map of value and its related data.
So, Which one is better in term of documentation, clarity and maintainability?
I’ve tried this and it returned the correct value
@Query("SELECT * FROM notes " +
"JOIN note_labels ON notes.id = note_labels.note_id " +
"JOIN labels ON note_labels.label_id = labels.id")
suspend fun getAllNotesWithLabels(): Map<Note, List<Label>>
@Query("SELECT * FROM labels JOIN note_labels ON labels.id = note_labels.label_id JOIN notes ON note_labels.note_id = notes.id")
suspend fun getAllLabelsWithNotes(): Map<Label, List<Note>>
Should I switch to use @Relation or keeping this approach?