android房间关系:缺少列



我在定义两个实体之间的关系时遇到问题。这种关系是一对一的。每个设备分配到一个房间。

设备实体:

@Entity
data class Device(
@PrimaryKey(autoGenerate = false) val ipAddress: String,
val deviceName: String,
val type: Int,
val uniqueRoomId: Int
) {
@Ignore
val status: DeviceStatus = DeviceStatus.Off
}

空间实体

@Entity
data class Room(
@PrimaryKey(autoGenerate = true) val roomId: Int,
val name: String
)

设备和房间对象:

data class DeviceAndRoom(
@Embedded val room: Room,
@Relation(
parentColumn = "roomId",
entityColumn = "uniqueRoomId",
entity = Device::class
)
val device: Device
)

DeviceDao:

@Dao
interface DeviceDao {
@Transaction
@Query("SELECT * FROM Device")
fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>
[...]
}

但我得到以下构建错误:

The columns returned by the query does not have the fields [roomId,name] in com.test.mytestapp.models.DeviceAndRoom even though they are annotated as non-null or primitive. Columns returned by the query: [ipAddress,deviceName,type,uniqueRoomId]

我遵循了官方的android指南,但是有更多的文章描述了相同的过程,例如:与Room的数据库关系

我不知道怎么了。也许有人有主意。

对于这种关系(房间(嵌入)与设备(关系)),您可以查询父元素:-

@Query("SELECT * FROM room")
fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>
  • 名称应该是RoomAndDevice

。它不能在设备表中找到roomid和name列,因为它们在房间表中。然后通过底层查询从每个检索到的房间检索设备,沿着SELECT * FROM the_relationship_entity WHERE entityColumn = parentColumn的行检索,因此建议使用@Trasnaction

如果你想要设备和他们的房间,那么你可以使用:-

data class DeviceAndRoom(
@Embedded val device: Device,
@Relation(
entityColumn = "roomId",
parentColumn = "uniqueRoomId",
entity = Room::class
)
val room: Room
)

和:-

@Transaction
@Query("SELECT * FROM Device")
fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>