android - 在房间数据库 android 中查询时合并两个实体

标签 android android-room

假设我们有用户和订单实体

@Entity
public class User{
   int id;
   String name;
}
@Entity
public class Order{
   int id;
   int userId;
   String meal;
}

所以当我查询时

@Query("SELECT * FROM users")
public List<User> loadUsers(); 

我想要这个输出:

{"user":{"id":"","name":"",
"order":{"id":"","userId":"","meal":""}}}

最佳答案

您可以使用Relation注释来解决此问题。注意,官方文档说[ official reference ]:

The type of the field annotated with Relation must be a List or Set.

@Entity
public class User{
   @PrimaryKey
   int id;
   String name;
   @Relation(parentColumn = "id", entityColumn = "orderId", entity = Order.class)
   List<Order> orders;
}

@Entity
public class Order{
   @PrimaryKey
   int id;
   int userId;
   String meal;
}

关于android - 在房间数据库 android 中查询时合并两个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882805/

相关文章:

android - 自定义数组适配器初始化错误

java - 如何在 Android Room 中写一个到(两个嵌入式实体的许多 pojo)

android - 构建后撤消 list 更改

android - 在我的应用程序类中声明的演示者中使用静态变量是个好主意吗

android - 使用 Kotlin 多行字符串和 Room 添加缩进后数据库迁移失败

android -room - 在房间数据库中保存对象

android - LifecycleRegistryOwner 类已弃用

android - 房间数据库迁移没有正确处理转换

android - Google map 中两点之间的多条路线

android - 如何使用 MOSHI 将 un json 字符串解析为列表