Room更新字段

You have to know which column you are matching against ahead of time as Room doesn't let you dynamically define the column. Let's say you've got an entity Person as follows:

@Entity(tableName = "people")
public final class Person {

    @PrimaryKey
    @ColumnInfo(name = "uuid")
    public final String uuid;

    @ColumnInfo(name = "name")
    public final String name;

    @ColumnInfo(name = "is_alive")
    public final Boolean isAlive;

    public Person(String uuid, String name, Boolean isAlive) {
        this.uuid = uuid;
        this.name = name;
        this.isAlive = isAlive;
    }
}

And you wanted to update the column is_alive depending on the name. You could write the method as:

@Query("UPDATE people SET is_alive= :alive WHERE name = :name")
public abstract int setIsAliveByName(String name, int alive);

This of course could get quite tedious if you have an entity which has many fields because you have to pass in each field as a separate parameter and write the entire UPDATE query by hand.

The alternative is to do a SELECT query to fetch the items first, update the objects with the new data and then save them back into the db.

It's at this point you start to wonder if using an ORM is actually making anything easier and is worth your time...

转载于:https://my.oschina.net/sfshine/blog/1605665

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值