更新android Room中实体的一些特定字段 [英] Update some specific field of an entity in android Room

查看:48
本文介绍了更新android Room中实体的一些特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的新项目使用 android 房间持久性库.我想更新表的某些字段.我在我的 Dao -

I am using android room persistence library for my new project. I want to update some field of table. I have tried like in my Dao -

// Method 1:

@Dao
public interface TourDao {
    @Update
    int updateTour(Tour tour);
}

但是当我尝试使用此方法进行更新时,它会更新实体中与游览对象的主键值相匹配的每个字段.我用过 @Query

But when I try to update using this method then it updates every field of the entity where it matches primary key value of tour object. I have used @Query

// Method 2:

@Query("UPDATE Tour SET endAddress = :end_address WHERE id = :tid")
int updateTour(long tid, String end_address);

它正在工作,但在我的情况下会有很多查询,因为我的实体中有很多字段.我想知道如何更新某些字段(不是全部),例如 Method 1 where id = 1;(id 是自动生成的主键).

It is working but there will be many queries in my case because I have many fields in my entity. I want to know how can I update some field (not all) like Method 1 where id = 1; (id is the auto generate primary key).

// Entity:

@Entity
public class Tour {
    @PrimaryKey(autoGenerate = true)
    public long id;
    private String startAddress;
    private String endAddress;
    //constructor, getter and setter
}

推荐答案

我想知道如何更新某些字段(不是全部),例如方法 1,其中 id = 1

I want to know how can I update some field(not all) like method 1 where id = 1

使用 @Query,就像您在方法 2 中所做的那样.

Use @Query, as you did in Method 2.

在我的情况下查询太长,因为我的实体中有很多字段

is too long query in my case because I have many field in my entity

然后有更小的实体.或者,不要单独更新字段,而是与数据库进行更粗粒度的交互.

Then have smaller entities. Or, do not update fields individually, but instead have more coarse-grained interactions with the database.

IOW,Room 本身没有任何东西可以满足您的需求.

UPDATE 2020-09-15:Room 现在有部分实体支持,可以帮助解决这种情况.请参阅此答案了解更多信息.

UPDATE 2020-09-15: Room now has partial entity support, which can help with this scenario. See this answer for more.

这篇关于更新android Room中实体的一些特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆