You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Room报错:Entities and POJOs must have a usable public constructor

Room Entity 包含List字段编译报错处理

问题代码

定义Kotlin data class作为Room实体代码如下:

@Entity(tableName = "training_session")
data class SessionEntity(
    @PrimaryKey(autoGenerate = false) val id: Long,
    @ColumnInfo(name = "current_state_marker") val currentState: Short,
    @Embedded val states: List<Int>
)

编译报错信息

> Task :training-infrastructure:kaptDebugKotlin FAILED
error: 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). - java.util.List
error: 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). - java.util.List

同项目内另一个写法类似、同样包含List字段的Entity未触发该报错。

解决方案

调整TypeConverter定义即可解决问题,调整后的代码如下:

data class SessionStateList (val stateList : List<Int>) 

class SessionStateListConverter {

    @TypeConverter
    fun fromArraySessionStateList(sh: List<Int>?): String? {
        return Gson().toJson(sh)
    }
    @TypeConverter
    fun toArraySessionStateList(sh: String?): List<Int>? {
        val listType: Type = object : TypeToken<ArrayList<Int?>?>() {}.type
        return Gson().fromJson(sh,listType)
    }
}

操作提示:需要将上述Converter注册到你的Room Database类上,同时删除List字段上的@Embedded注解,@Embedded仅支持自定义POJO类型,无法作用于集合类型。

补充说明

之前提到的未报错的包含Embedded val something: List<Int>的Entity,实际是因为没有被添加到@Database注解的实体列表中,所以才没有触发编译错误。

内容的提问来源于stack exchange,提问作者hba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:06:03