我正在使用Room,发现将主键设置为“自动生成”有问题,
如果执行插入操作,然后再执行更新操作,则这些操作生成的键会有所不同,因此,我的数据不会得到更新。
@Entity(tableName = "test_table")
public class TestEntity {
@PrimaryKey(autoGenerate = true)
private int uid;
@ColumnInfo(name = "expiration_date_access_token")
private String expirationDateAccessToken;
/**
* Getter for retrieving primary key
*
* @return Primary key
*/
public int getUid() {
return uid;
}
/**
* Setter for setting primary key
*
* @param uid Primary key
*/
public void setUid(int uid) {
this.uid = uid;
}
/**
* Getter for retrieving expiration date of access token
*
* @return Expiration date of access token
*/
public String getExpirationDateAccessToken() {
return expirationDateAccessToken;
}
/**
* Setter for setting expiration date of access token
*
* @param expirationDateAccessToken Expiration date of access token
*/
public void setExpirationDateAccessToken(String expirationDateAccessToken) {
this.expirationDateAccessToken = expirationDateAccessToken;
}
}
下面是一个例子
@Dao
public interface TestDao {
@Query("SELECT * FROM test_table")
List<TestEntity> getAll();
@Query("DELETE FROM test_table")
void deleteAll();
@Insert
void insert(TestEntity testEntity);
@Delete
void delete(TestEntity testEntity);
@Update
void update(TestEntity testEntity);
}
@Database(entities = {TestEntity.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "room.test.db";
private static AppDatabase APP_DATABASE_INSTANCE;
public abstract TestDao testDao();
public static AppDatabase getAppdatabase(@NonNull Context context) {
if (FrameworkUtils.checkIfNull(APP_DATABASE_INSTANCE)) {
APP_DATABASE_INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME).build();
}
return APP_DATABASE_INSTANCE;
}
/**
* Method is used to destroy database instance
*/
public static void destroy() {
APP_DATABASE_INSTANCE = null;
}
}
我已经将我的LiveData连接到了我的存储库,然而,出于以下过于简单的原因,我也执行了相同的操作。
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// update database tables
TestEntity testEntity = new TestEntity();
// if I uncomment setting uid, which is the hardcoded primary key
// value, the update will happen. If I do not include this, and
// just try to update my data, a new primary key is generated and
// the old data does not get updated.
// testEntity.setUid(1);
testEntity.setExpirationDateAccessToken("12345");
AppDatabase.getAppdatabase(context).testDao().update(testEntity);
}
});
@PrimaryKey(autoGenerate = true)
private int uid = 1; <---- works with any hardcoded int value