Android Room Database忽略问题“尝试了以下构造函数,但它们不匹配”

问题描述

我的实体类别:

@Entity(tableName = "student")
data class Student(
    var name: String,var age: Int,var gpa: Double,var isSingle: Boolean,@PrimaryKey(autoGenerate = true)
    var id: Long = 0,@Ignore                           //don't create column in database,just for run time use
    var isSelected: Boolean = false                     
)

然后我像这样插入(在androidTest中测试):

val student = Student("Sam",27,3.5,true)

studentDao.insert(student)

在添加@Ignore批注之后,它立即给我这个错误:

C:\Android Project\RoomTest\app\build\tmp\kapt3\stubs\debug\com\example\roomtest\database\Student.java:7: ����: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
public final class Student {
         ^
  Tried the following constructors but they failed to match:
  Student(java.lang.String,int,double,boolean,long) -> [param:name -> 
matched field:name,param:age -> matched field:age,param:gpa -> matched 
field:gpa,param:isSingle -> matched field:isSingle,param:isSelected -> 
matched field:unmatched,param:id -> matched field:id][WARN] Incremental 
annotation processing requested,but support is disabled because the 
following processors are not incremental: androidx.room.RoomProcessor 
(DYNAMIC).

解决方法

由于Room仍在编译期间生成Java类,并且问题出在默认值参数上,因此请尝试使用@JvmOverloads作为构造函数:

@Entity(tableName = "student")
data class Student @JvmOverloads constructor(
    var name: String,.....  

更新

有趣的是,here in documentation对此案没有提及特殊待遇。并且this issue已经存在,可以修复此文档。

this issue到问题本身的结论是:

使用@JvmOverloads应该可以。在不远的将来有一天,我们可能会生成Kotlin,这不会成为问题

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...