Problems and solutions that occur when using Jetpack Room

Without further ado, let’s look at examples:

@Query("SELECT * FROM precious WHERE name LIKE :searchContent OR remark LIKE :searchContent")
  fun find(searchContent: String): MutableList<Precious>

A method in interface DAO. The name and remark in the query table contain the data of the search content. If you write it like this, you cannot find the data. The SQL is written like this:

SELECT * FROM precious WHERE name LIKE %searchContent% OR remark LIKE %searchContent%

So I took it for granted and added % to the statement in @Query, and it turned out like this %:searchContent%, and an error was reported.
Finally, I searched around and saw a solution on stackoverflow. It doesn't feel official enough, but it does work.
Solution: find(searchContent: String)When calling a function, add % to the passed parameters:

dataList = preciousDao.find("%$it%")

Another problem:

The primary key of the entity class is set to autogenerate. The constructed entity class must be passed in when idusing the function to insert data . However, this conflicts with the automatically generated primary key and also affects the use of subsequent functions. Solution: Set it to be nullable. The default value is , build The entity class is passed in , so it's ok.insertidupdate
idnullnull

@Entity
data class Precious (
    @PrimaryKey(autoGenerate = true)
    val id: Long? = null,
    @ColumnInfo(name="name") val name: String,
    @ColumnInfo(name="type") val type: PreciousType,
    @ColumnInfo(name="remark") val remark: String?
)
 val precious = Precious(null,
                    binding.etName.editableText.trim().toString(),
                    type,
                    binding.etRemark.editableText.trim().toString()
                )
                dao.insert(precious)

Guess you like

Origin blog.csdn.net/u012175780/article/details/130247288