For this transaction Query in Android Room :
@Transaction
@Query("SELECT * FROM TPAGroup WHERE zuid=:zuid ORDER BY `index`")
fun getGroupWithSecretsForZuid(zuid: String): List<TPAGroupWithSecrets>
and this as my data class :
data class TPAGroupWithSecrets(
@Embedded val group: TPAGroup,
@Relation(
parentColumn = "groupId",
entityColumn = "groupId"
)
var secrets: MutableList<TPASecrets>
)
I get the TPAGroup in the right order , but TPASecrets have not been ordered ! How can i get both of them in right order , ordered by their index ( which is a column common to both tables ) ?
When
@Relationis used, Room gets the related objects, as you have found, without any specific order (the order will likely be by the primary key but that depends upon SQLite's query optimiser).If you need them ordered you can either
Here's a Working Example of 2
TPAGroup (made up)
TPASecrets (made up)
TPAGroupWithSecrets (uncanged)
An @Dao annotated class
an @Database annotated class to tie all the Room stuff together TheDatabase
Finally putting it into action in an Activity:-
The result output to the log (noting that the data has been purposefully inserted to demonstrate sorting):-
Partial Example of option 3
A query such as
Would produce data (using the data loaded by the working example):-
You would then need to have a POJO to receive the data. However there's an issue with duplicate columns names index and groupid so the query is more complicated requiring aliases (AS) e.g. you could use
So the duplicated groupid (which would always have the same value in both) is dropped from TPASecrets and the TPASecrets column is aliased/renamed as secretsIndex. Obviously the POJO would have to cater for this.
You then have to build each TPAGroup with it's TPASecrets by looping through the results.
Not done/shown as most tend to opt for option 1 or 2 and tend to baulk at option 3. However, option 3 is probably the more efficient as there is just the single query (no need for @Transaction).