Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Map object by DAO method

I would like to have method like this in my dao object

@Query("SELECT c.name, sum(p.value) FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>

but i get the error

error: Not sure how to convert a Cursor to this method's return type public abstract java.util.Map

Is it possible to change it to working version?

So it can be different type to return but the main conditions are

  1. It must be only one query in db
  2. I would like to avoid extra code like creating additional data structure only for this method
like image 207
Ilia Vladimirskiy Avatar asked Jul 19 '26 01:07

Ilia Vladimirskiy


1 Answers

I'm little late for a party but maybe someone will still search for it.

From Room 2.4 we are able to use multimap return type with annotation @MapInfo which allow us to define the mapping for key and value.

In your case it will be sth like this:

@MapInfo(keyColumn = "name", valueColumn = "sum")    
@Query("SELECT c.name AS name, sum(p.value) AS sum FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>

More info: https://developer.android.com/training/data-storage/room/accessing-data#multimap

Update

@MapInfo was deprecated. Here's the new way to do it in Kotlin:

@Query("SELECT c.name AS name, sum(p.value) AS sum FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
suspend fun getCategoryStats(): Map<@MapColumn(columnName = "name") String, @MapColumn(columnName = "sum") Float>
like image 110
Warcello Avatar answered Jul 21 '26 15:07

Warcello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!