新行的插入ID损坏

时间:2018-10-06 17:00:27

标签: android sqlite sequence android-room

我正在使用Room。 我有这个插入方法:

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Month month);

我的插入方法:

for(...){
...
monthDao.insert(new Month(0, monthTitle, monthUrl));
}

也是我的模特

@Entity(tableName = "news_month_table", indices = @Index(value = {"month_index"}, unique = true))
public class Month {

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "month_id")
@Getter @Setter
public long month_id;
@ColumnInfo(name = "month_name")
@Getter @Setter
public String monthName;
@ColumnInfo(name = "month_url")
@Getter @Setter
public String monthURL;
@ColumnInfo(name = "month_index")
@Getter @Setter
public int monthIndex;

我的情况: 1)启动应用程序并下载+插入数据(for()的12个回合) 现在base是正确的,包含12行ID为1-12的行。 2)我有新数据(例如一行)。启动应用程序,然后下载并插入数据。 现在base包含13行,其ID为1-12和24。

我不知道出什么问题,请帮忙

2 个答案:

答案 0 :(得分:1)

您可以通过以下代码插入新元素:

MonthDao.insert(new Month(monthDao.getLastMonthId()+1, monthTitle, monthUrl, mIndex));

...

@Query("SELECT * FROM news_month_table ORDER BY month_id DESC LIMIT 1;")
int getLastMonthId();

只是解决问题的方法。

答案 1 :(得分:0)

我认为问题在于monthIndex属性的唯一索引。请检查如何设置此属性的值。在数据库中检查关联列的值。