Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room partly update if exit

I ran across a problem where I am not really sure how to solve it. The project I am working on currently has a model which partly consists of backend stored data and data from the local database. So what I am trying to Archive is something like that:

Article : [Bunch of Information] & [boolean Subscribed]

The subscribed field is device bound and should not reflect any data on the backend. My question is if it is possible to implement in Room some kind of createIfNotExit() Method that handles the following cases:

  • Article not present locally: store a copy and set Subscribed to false
  • Article present: update all the Information and Keep the Subscribe-Flag untouched

My idea is to split the model into a separate Subscription-Model holding a reference to the Article. This way I could implement it simply via @Update(OnConfict=Update) etc...

Is there a way to implement a simple @Query method in the DAO that performs what I want?

Sorry if this is a really basic question but I couldn't find any material about best practices handling this case.

Thank you in advance!

like image 679
maperz Avatar asked Oct 17 '22 09:10

maperz


1 Answers

For example, your entity is:

@Entity(tableName = "articles")
public final class Article {
    @PrimaryKey
    public long serverId;
    public String title;
    public String url;

    public boolean isSubscribed;
}

You may write this method in DAO:

@Query("INSERT OR REPLACE INTO articles (serverId, title, url, isSubscribed) VALUES (:id, :title, :url,
    COALESCE((SELECT isSubscribed FROM articles WHERE id = :id), 0));")
void insertOrUpdateArticle(long id, String title, String url);

Another option - write this logic in your repository and use two simple operations: select and update

like image 89
DeKaNszn Avatar answered Oct 21 '22 00:10

DeKaNszn