我正在传递国家/地区的国家/地区列表,以使用 Room 将其保存在数据库中。它保存了,但它复制了值,并且 OnConflict Replace 策略不起作用。
AppDatabase.getAppDatabase(getApplicationContext()).countryDao().insertAllList(countryList);
即使我传递了以下替换策略,列表值也会重复。
@Insert(onConflict = OnConflictStrategy.REPLACE)
这里是 CountryDao
@Dao
public interface CountryDao {
@Query("SELECT * FROM country")
List<Country> getAllCountries();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllList(List<Country> countries);
}
国家/地区对象:
@Entity(tableName = "country")
public class Country {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@PrimaryKey(autoGenerate = true)
private int id;
private long countryId;
private String countryName;
public long getCountryId() {
return countryId;
}
public void setCountryId(long countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
最佳答案
您必须为每个国家/地区拥有不同的 ID 并手动分配它,否则每个元素将具有 id=0 并覆盖另一个元素。
尝试不使用自动生成 key
@PrimaryKey(autoGenerate = false)
private int id;
关于android - 使用 Room 复制 Android 中的值在 Insert 命令上传递列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691276/