首页 > 解决方案 > 如何嵌入不直接相关的 Room 实体?

问题描述

我有三个基本实体来表示我的 Room 数据库中的表:CountryStateCity

为了在一个州内嵌入城市列表,我创建了一个名为StateWithCities的 POJO :

package org.example.roomtest;

import java.util.List;
import androidx.room.Embedded;
import androidx.room.Relation;

public class StateWithCities {

    @Embedded
    public State state;

    @Relation(
            parentColumn = "_id", // This is the `states`.`_id` column.
            entityColumn = "state_id" // This is the `cities`.`state_id` column.
    )
    public List<City> cities;
}

然后我可以从我的StateDao界面中的查询返回:

@Query("SELECT * FROM `states`")
LiveData<List<StateWithCities>> getAllStatesWithCities();

但是,我现在想在我的CountryDao界面中创建一个查询,该查询可以返回与某个国家/地区关联的城市。

(国家和城市通过states表格相关联。所以,正如您所料,cities.state_idstates.相关,_id并且states.country_idcountries. _id. 相关)

所以我创建了一个CountryWithStatesWithCities POJO:

package org.example.roomtest;

import java.util.List;
import androidx.room.Embedded;
import androidx.room.Relation;

public class CountryWithStatesWithCities {

    @Embedded
    public Country country;

    @Relation(
            parentColumn = "_id", // This is the `country`.`_id` column.
            entityColumn = "country_id" // This is the `states`.`country_id` column.
    )
    public List<StateWithCities> stateWithCities;
}

在这一点上,一切都编译得很好。但是当我将此查询添加到CountryDao时:

@Query("SELECT * FROM `countries`")
LiveData<List<CountryWithStatesWithCities>> getAllCountriesWithStatesWithCities();

我得到这些引用我的两个类的编译错误,上面:

> ...StateWithCities.java:7: error: The class must be either @Entity or @DatabaseView.
> public class StateWithCities {
>        ^

> ...CountryWithStatesWithCities.java:16: error: Cannot find the child entity column `country_id` in org.team_love.shapethefuture.roomtest.StateWithCities. Options: 
>     public List<StateWithCities> stateWithCities;
>                                  ^

这些错误似乎告诉我我的CountryDao接口需要引用实体(或 DatabaseViews)而不是 POJO。那么,解决我的要求的正确方法是什么:如何嵌入不直接相关的 Room 实体?

标签: androidandroid-room

解决方案


你需要设置你的实体类显式描述CountryWithStatesWithCities,因为 Room 有一个问题来从上下文中推断它:

public class CountryWithStatesWithCities {

    @Embedded
    public Country country;

    @Relation(
            entity = State.class, <- this should be added explicitly
            parentColumn = "_id", // This is the `country`.`_id` column.
            entityColumn = "country_id" // This is the `states`.`country_id` column.
    )
    public List<StateWithCities> stateWithCities;
}

推荐阅读