本文介绍了插入新行时,Android Room FOREIGN KEY约束失败(代码787)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我关注了这篇帖子 Android Room FOREIGN KEY约束失败(代码787 ).不幸的是,对于我来说,它不起作用.
I followed this post Android Room FOREIGN KEY constraint failed (code 787). Unfortunately, it not works in my case.
尝试插入新的记事时,我总是会收到错误消息.当然,数据库中存在一个主题.
I always get the error when trying to insert a new Note. Of course, there is a Topic existed in Database.
你们有什么主意吗?
请在下面查看我的代码.
Please take a look at my code below.
主题:
@Entity(tableName = "topic")
data class Topic(@PrimaryKey var id: Long? = null,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "note_count") var noteCount: Int = 0,
@ColumnInfo(name = "view_count") var viewCount: Long = 0) : Serializable {
@Ignore
var notes: List<Note>? = null
}
注意:
@Entity(tableName = "note",
foreignKeys = arrayOf(ForeignKey(entity = Topic::class,
parentColumns = arrayOf("id"), childColumns = arrayOf("topic_id"), onDelete = ForeignKey.CASCADE)))
@TypeConverters(TimestampConverter::class)
data class Note(@PrimaryKey(autoGenerate = true) var noteId: Long? = null,
@ColumnInfo(name = "topic_id") var topicId: Long? = null,
@ColumnInfo(name = "title") var title: String,
@ColumnInfo(name = "caption") var caption: String? = "",
@ColumnInfo(name = "created_at") var createdAt: Date? = null) : Serializable {
}
NoteDao:
@Dao
interface NoteDao {
@Query("SELECT * from note")
fun getAll(): LiveData<List<Note>>
@Insert(onConflict = REPLACE)
fun insert(note: Note)
@Query("DELETE from note")
fun deleteAll()
@Delete
fun delete(category: Note)
@Query("SELECT * FROM note WHERE title = :title COLLATE NOCASE LIMIT 1")
fun findNoteByTitle(title: String): Note?
@Query("SELECT * FROM note WHERE topic_id = :topicId")
fun findNotesByTopicId(topicId: Long): LiveData<List<Note>>
@Query("SELECT count(*) FROM note WHERE topic_id = :topicId")
fun countNotesByTopicId(topicId: Long): Long
@Update(onConflict = IGNORE)
fun update(category: Note)
}
推荐答案
我发现了问题.因为我已经创建了2个不同的数据库:TopicDataBase和NoteDataBase.
I found the problem. Because I have been created 2 different Databases: TopicDataBase and NoteDataBase.
所以我只需要删除其中1个即可.我的坏人><
So I just need to remove 1 of them.My bad >"<
这篇关于插入新行时,Android Room FOREIGN KEY约束失败(代码787)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!