更新android Room中实体的某些特定字段

新手上路,请多包涵

我正在为我的新项目使用 android 房间持久性库。我想更新表格的某些字段。我在我的 Dao 中尝试过

// Method 1:

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

但是,当我尝试使用此方法进行更新时,它会更新与旅游对象的主键值匹配的实体的每个字段。我用过 @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 是自动生成的主键)。

 // Entity:

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

原文由 Rasel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.3k
2 个回答

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

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

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

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

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

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

原文由 CommonsWare 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 URI 通过 id 更新数据库中的行

Tour tourEntity = new Tour();
tourEntity.end_address = "some adress";
tourEntity.start_address= "some adress";
//tourEntity..... other fields
tourEntity.id = ContentUris.parseId(Uri.parse("content://" + BuildConfig.APPLICATION_ID + File.separator + id));
//get your updatemethod with abstract func in your database class (or with another way, wich you use in project)
int tourDaoUpdate = getInstance(context).tour().update(tourEntity);

您还应该添加到您的更新方法 OnConflictStrategy

 @Update(onConflict = OnConflictStrategy.REPLACE)
int updateTour(Tour tour);

原文由 B3ACOC 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题