使用 Room 复制 Android 中的值在 Insert 命令上传递列表
passing list on Insert command using Room duplicating the values in Android
我正在传递 countryList of Country 以使用 Room 将其保存在数据库中。它保存但复制值和 OnConflict 替换策略不起作用。
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 并覆盖另一个。
尝试不使用自动生成密钥
@PrimaryKey(autoGenerate = false)
private int id;
我正在传递 countryList of Country 以使用 Room 将其保存在数据库中。它保存但复制值和 OnConflict 替换策略不起作用。
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 并覆盖另一个。
尝试不使用自动生成密钥
@PrimaryKey(autoGenerate = false)
private int id;