Home > OS >  How Select From Multiple Entity into a new Object with Room-Database?
How Select From Multiple Entity into a new Object with Room-Database?

Time:06-03

I Have this tow POJOs For RoomDB Entity

@Entity
public class Favorite {...}
@Entity
public class ProductCart {
    Integer productQuantity;
    ...
}

I need to apply this select statment and return it inside the object FavoriteAdapterData

SELECT favorite.*,
       (SELECT CASE count(productQuantity)
               WHEN 0 THEN 0
                      ELSE productQuantity
               END  FROM ProductCart 
        WHERE favorite.id = productId) AS cartQuantity
FROM Favorite favorite

Sqlite statment test

public class FavoriteAdapterData {
    int cartQuantity = 0;
    Favorite favorite;
    ...
}

I try the following code

@Query("SELECT  "  
            "      (    SELECT CASE count(productQuantity) "  
            "           WHEN 0  THEN 0 "  
            "                   ELSE productQuantity  "  
            "           END  "  
            "           FROM ProductCart "  
            "           WHERE productId = favorite.id"  
            "       ) AS cartQuantity"  
            "       ,favorite.* "  
            "FROM Favorite favorite")
    LiveData<List<FavoriteAdapterData>> getFavoriteProducts();

But It didn't work and Android Studio notfi me this error:

Cannot figure out how to read this field from a cursor. 
Favorite favorite; 
             ^

CodePudding user response:

You need to Embed the Favorite class within the FavoriteAdapterData class using the @Embedded annotation, then it will determine the columns and outputfields from the Favorite class's fields/variables

e.g. :-

public class FavoriteAdapterData {
    int cartQuantity = 0;
    @Embedded
    Favorite favorite;
    ...
}

CodePudding user response:

You should define a custom DatabaseConverter class to let Room know how to convert the Favorite instance:

class DatabaseConverter {
    @TypeConverter
    fun fromFavorite(favorite: Favorite) : String = Gson().toJson(favorite)
    @TypeConverter
    fun toFavorite(value: String) : Favorite {
        val type = object : TypeToken<Favorite>() { }.type
        return Gson().fromJson(value, type)
    }
}

You will just need to declare this TypeConverter in your database declaration:

@Database(...)
@TypeConverters(DatabaseConverter::class)
abstract class YourDatabase : RoomDatabase() { ... }

Make sure to add the Gson library to your application.

  • Related