Room更新字段

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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

你可能感兴趣的:(Room更新字段)