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

Kotlin RoomDB使用@Relation关联非@Entity类报错如何解决

报错原因

Room的@Relation注解默认会将关联字段的返回类型当做数据库实体类校验,你返回的StructuralObjectItemDB是组合了实体和子关联的POJO类,没有加@Entity注解,因此触发校验失败。

解决方法

按以下两步修改代码即可:

  1. 移除StructuralObjectItemDB中冗余的buildingItemId字段:@ColumnInfo注解仅作用于@Entity实体类的字段,放在非实体POJO中无效,且该字段已经包含在StructuralObjectItemEntityDB的buildingId属性中。
  2. 给BuildingItemDB中关联structuralObjectEntities的@Relation注解显式指定entity参数为对应的实体类StructuralObjectItemEntityDB::class,同时修正关联的外键字段名:StructuralObjectItemEntityDB中关联建筑ID的字段是buildingId,而非你之前写的buildingItemId。

修改后的StructuralObjectItemDB.kt

package com.example.data.roomDB.entities.buildingItem.structuralObjectItem

import androidx.room.*
import com.example.data.roomDB.entities.buildingItem.structuralObjectItem.iconItem.IconItemEntityDB

data class StructuralObjectItemDB(
    @Embedded
    val structuralItemsEntityDB: StructuralObjectItemEntityDB,

    @Relation(
        parentColumn = "id",
        entityColumn = "structuralObjectItemId"
    )
    val icon: IconItemEntityDB
)

修改后的BuildingItemDB.kt

package com.example.data.roomDB.entities.buildingItem

import androidx.room.Embedded
import androidx.room.Relation
import com.example.data.roomDB.entities.buildingItem.adressItem.AddressItemEntityDB
import com.example.data.roomDB.entities.buildingItem.structuralObjectItem.StructuralObjectItemDB
import com.example.data.roomDB.entities.buildingItem.structuralObjectItem.StructuralObjectItemEntityDB

data class BuildingItemDB (
    @Embedded
    val buildingItemEntityDB: BuildingItemEntityDB,

    @Relation(
        entity = StructuralObjectItemEntityDB::class, // 显式指定关联的实体类
        parentColumn = "id",
        entityColumn = "buildingId" // 修正为实体中实际的外键字段名
    )
    val structuralObjectEntities: List<StructuralObjectItemDB>,

    @Relation(
        parentColumn = "id",
        entityColumn = "buildingItemId"
    )
    val address: AddressItemEntityDB
)

配置完成后重新编译即可,Room 2.2.0及以上版本原生支持嵌套Relation POJO的自动组装,你原有的DAO方法已经添加了@Transaction注解,无需额外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:36:00