【问题标题】:Android Room using Update but not set All Column in entityAndroid Room 使用更新但未在实体中设置所有列
【发布时间】:2018-07-30 13:41:17
【问题描述】:

实体发送更新表中的房间忽略数据是否为空?! 我想更新实体中的部分列,但我将新数据存储在实体类中并将其发送到 DAO 中的更新是否替换该行中的其他数据?!

例如,如果实体类是:

@Entity(tableName = "ITEM_TABLE")
public class Item
{
    @PrimaryKey
    @NotNull
    @ColumnInfo(name = "ID")
    public int id;

    @ColumnInfo(name = "COLUMN_TITLE")
    public String title;

    @ColumnInfo(name = "COLUMN_WEIGHT")
    public String weight;
}

和这样的更新请求:

Item item = new Item();
item.title = "new Title";
item.id = 2;
ItemDAO.update(item);

如果存在 id = 2 的实体并且它的权重 = "250" 如果我​​以这种方式更新它会发生什么?!

【问题讨论】:

  • 这里的权重会变为null。如果您需要执行某种仅限于某些列的更新,请使用@Query

标签: android android-room


【解决方案1】:

尝试定义自己的 DAO。

@Dao
public interface IDaoAccessStuff {

    @Query("UPDATE SET COLUMN_TITLE=:text WHERE id=:id")
    void UpdateColumnById (String text, int id);
    ...
    @Insert
    void insertStuff (Stuffstuff);

    @Update
    void updateExercise (Exercises exercise);
}

然后:

@Database (entities = {Stuff.class}, version = 1, exportSchema = false)
public abstract class AStuffDatabase extends RoomDatabase {
    public abstract IDaoStuffExercise daoAccess();
}

最后:

private AStuffDatabase aStuffDatabase;
...
RoomDatabase.Builder<AExerciseDatabase> builder;
builder = Room.databaseBuilder(getApplicationContext(),
           AStuffDatabase.class,
            YOUR_DATABASE_NAME);
aStuffDatabase = builder.fallbackToDestructiveMigration().build();
... 
aStuffDatabase.daoAccess().updateStuff(yourString, theId);

另外,除非您指定该列不应接受空值,如下所示:

@ColumnInfo(name = "COLUMN_TITLE")
@NonNull 
private String title;

【讨论】:

  • 感谢您的回答,但问题不在于 Null 值。问题是房间每次我们调用更新时都会替换所有项目的值。我只想更新一列数据。
  • @mohmadaliYaghmay,我更新了我的答案。看看并尝试一下。
猜你喜欢
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2021-08-01
相关资源
最近更新 更多