我正在使用 RoomDb 将消息存储在使用房间数据库的设备中。每个消息都包含一个唯一的 Id,它是在服务器上存储消息时生成的。 当一条消息被下载并存储在房间数据库中时,如果我再次尝试下载该消息,它就会被下载并保存到房间数据库中。
我试过使用替换策略,但还是不行
@Insert(onConflict = OnConflictStrategy.REPLACE)
void saveMessage(ArrayList<Message> messages);
上面的代码应该替换现有的消息,但它并没有这样做。
消息模型如下所示。
public class Message {
@Exclude
@PrimaryKey(autoGenerate = true)
public long _id;
@Exclude
@ColumnInfo(name = "messageId")
public String id;
@Exclude
public boolean outbox;
@Exclude
public boolean pending;
@Exclude
public boolean draft;
@Exclude
@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
public byte[] thumbnail;
@Exclude
public boolean downloaded;
@Exclude
public boolean seen;
@Exclude
public boolean liked;
@Exclude
public boolean disliked;
@Exclude
public String path; // Local attachment path
@Exclude
public String localFilePath; //Local attachment file path
public String title;
public String body;
public String type;
public String image;
public String file;
public String audio;
public String video;
}
最佳答案
你必须像这样改变你的实体类
在 Java 中
@Entity(tableName = "chat_message_table", indices = @Index(value = {"messageId"}, unique = true))
public class Message {
...
}
在 Kotlin 中
@Entity(tableName = "chat_message_table", indices = [Index(value = ["messageId"], unique = true)])
data class Message(@ColumnInfo(name = "messageId") val messageId: String) {
@PrimaryKey(autoGenerate = true)
var _Id: Int = 0
...
}
关于java - 如何避免在 Room Db 的表中重复输入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829672/