barryalan2633
barryalan2633

Reputation: 840

using member variable for query in Room

I want to update this Recipe object's recipeName

@Entity
data class Recipe(
    @PrimaryKey
    val recipeName: String,
    val image: String?
)

and so I tried doing a custom query, but android studio complains that I need Indexed, Not, or Set before the where clause

@Query("UPDATE Recipe WHERE recipeName = :oldName ")
suspend fun update(recipe: Recipe, oldName: String)

and so I tried doing it this way instead, problem is I don't know how to access the recipeName through the recipe object parameter in the function so I can use it on the query. I don't even know if this is possible.

   @Query("UPDATE Recipe SET recipeName = :recipe.recipeName WHERE recipeName = :oldName  ")
    suspend fun update(recipe: Recipe, oldName: String)

Just to clarify this doesn't work but that's what I am trying to achieve -> recipe.recipeName

Of course I could just pass in the new name instead of the whole recipe object and that would solve this but then I'd have to pass in every variable of my Recipe entity and this might grow out of hand if it grows too much so I would rather not if I have a choice...

Upvotes: 0

Views: 151

Answers (1)

sergiy tykhonov
sergiy tykhonov

Reputation: 5103

Consider next way:

  1. Change Recipe structure - add autogenerated id (Int) as a Primary Key, recipeName would be ordinary field.
  2. To change your Recipe in your code first you should get previous version of Recipe object (if you don't have it already):
@Query("SELECT * from Recipe WHERE recipeName = :oldName")
suspend fun getRecipeByName(oldName: String): Recipe?

and then you can change whatever fields you want (name and so on) and save changes with

@Update
suspend fun updateRecipe(recipe: Recipe)

You can do that since id of the object wouldn't change

Upvotes: 1

Related Questions