Search code examples
androiddatabasekotlinandroid-roomdao

Android rooms get data from database


I have a table, that I also use as a junction.

@Entity(tableName= "table_ref", primaryKeys = ["zutatid", "rezeptid"])
data class RefZutatRezept(
    val zutatid: Int,
    val rezeptid: Int,
    val menge: String
)

I want to write a function in my Dao, which I give a rezeptid and get all Pairs of "zutatid" an "menge". Do I have to write an own data class for this or what is the best way to do it?


Solution

  • Do I have to write an own data class for this or what is the best way to do it?

    If I understand correctly, then NO (but you could), you have a suitable class.

    Assuming that you have

     @Query("SELECT * FROM table_ref WHERE rezeptid=:rezeptid")
    

    then you can retrieve using the table's class e.g.

    fun theFunction(rezeptid: Int): List<RefZutatRezept>
    
    • you would have the additional rezeptid value, which would always be the same value, along with the pairs you want.

    Of course you could create a class/data class that only has the two values e.g.

    data class ZutatMengePairs(
        val zutatid: Int,
        val menge: String
    )
    

    and then use:-

     @Query("SELECT zutatid,menge FROM table_ref WHERE rezeptid=:rezeptid")
     fun theFunction(reseptid: Int): List<ZutatMengePairs>
    

    or even use

    @Query("SELECT * FROM table_ref WHERE rezeptid=:rezeptid")
    fun theFunction(reseptid: Int): List<ZutatMengePairs>
    
    • in this case you will get a build warning that not all the retrieved columns are used. e.g.

      warning: The query returns some columns [rezeptid] which are not used by .... .ZutatMengePairs. You can use @ColumnInfo annotation on the fields to specify the mapping. You can annotate the method with @RewriteQueriesToDropUnusedColumns to direct Room to rewrite your query to avoid fetching unused columns. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: zutatid, rezeptid, menge. public abstract java.util.List<ZutatMengePairs> getZutatMengePairsAlternate();