Update some specific field of an entity in android Room

前端 未结 7 1622
臣服心动
臣服心动 2020-11-29 16:45

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         


        
7条回答
  •  北海茫月
    2020-11-29 17:31

    According to SQLite Update Docs :

    
    @Query("UPDATE tableName SET 
        field1 = :value1,
        field2 = :value2, 
        ...
        //some more fields to update
        ...
        field_N= :value_N
        WHERE id = :id)
    
    int updateTour(long id, 
                   Type value1, 
                   Type value2, 
                   ... ,
                   // some more values here
                   ... ,
                   Type value_N);
    

    Example:

    Entity:

    @Entity(tableName = "orders")
    public class Order {
    
    @NonNull
    @PrimaryKey
    @ColumnInfo(name = "order_id")
    private int id;
    
    @ColumnInfo(name = "order_title")
    private String title;
    
    @ColumnInfo(name = "order_amount")
    private Float amount;
    
    @ColumnInfo(name = "order_price")
    private Float price;
    
    @ColumnInfo(name = "order_desc")
    private String description;
    
    // ... methods, getters, setters
    }
    

    Dao:

    @Dao
    public interface OrderDao {
    
    @Query("SELECT * FROM orders")
    List getOrderList();
    
    @Query("SELECT * FROM orders")
    LiveData> getOrderLiveList();
    
    @Query("SELECT * FROM orders WHERE order_id =:orderId")
    LiveData getLiveOrderById(int orderId);
    
    /**
    * Updating only price
    * By order id
    */
    @Query("UPDATE orders SET order_price=:price WHERE order_id = :id")
    void update(Float price, int id);
    
    /**
    * Updating only amount and price
    * By order id
    */
    @Query("UPDATE orders SET order_amount = :amount, price = :price WHERE order_id =:id")
    void update(Float amount, Float price, int id);
    
    /**
    * Updating only title and description
    * By order id
    */
    @Query("UPDATE orders SET order_desc = :description, order_title= :title WHERE order_id =:id")
    void update(String description, String title, int id);
    
    @Update
    void update(Order order);
    
    @Delete
    void delete(Order order);
    
    @Insert(onConflict = REPLACE)
    void insert(Order order);
    }
    

提交回复
热议问题