在特定的ID Room Android上插入行

时间:2018-02-19 18:27:20

标签: java android sqlite caching android-room

我正在尝试使用Android的SQLite包装器Room在特定ID处插入一行。

基本上,用例是我从服务器获取一行数据,并且我想使用远程行的ID作为Room中本地存储行的主键。

代码:

@Entity
class UserModel {
    @PrimaryKey
    public int id;

    public String firstName;
    public String lastName;
}
@Dao
public interface UserDAO {

    /**
     * Select all Users from the User table.
     *
     * @return all users.
     */
    @Query("SELECT * FROM " + UserRoomDB.TABLE_NAME)
    UserModel getUser();


    /**
     * Insert a user in the database. If the user already exists, replace it.
     *
     * @param user the user to be inserted.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(UserModel user);

    /**
     * Update a user.
     *
     * @param user task to be updated
     * @return the number of users updated. This should always be 1.
     */
    @Update
    int updateUser(UserModel user);

}
private void cacheUser(UserModel userModel){
        UserRoomDB db = Room.databaseBuilder(this.appContext,
                UserRoomDB.class, UserRoomDB.DB_NAME).build();
        db.userDAO().insertUser(userModel);
}

1 个答案:

答案 0 :(得分:0)

据我了解,您希望数据来自远程服务器,并将从那里接收到的响应id设置到本地数据库的行中。

如果这是您想要的,那么除了在@PrimaryKey上设置UserModel批注之外,还应该将autoGenerate设置为false。

@Entity
class UserModel {
    @PrimaryKey(autoGenerate = false)
    public int id;

    public String firstName;
    public String lastName;
}

这样做您的ID不会由Room自动生成,您可以在从远程源获取ID后立即设置ID,然后使用当前的insertUser()对象调用DAO的UserModel函数。