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

查看:561
本文介绍了更新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,其中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

与方法2一样,使用@Query.

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

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, there is nothing in Room itself that will do what you seek.

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

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