让我们举一个基本的例子
用于存储用户的表
@Entity (tableName="users")
class UsersEntity(
@PrimaryKey val id
var name:String,
...
)
用于存储角色的表
@Entity (tableName="roles")
class RolesEntity(
@PrimaryKey val id
var name:String,
...
)
用于存储用户和角色之间多对多关系的表
@Entity (tableName="roles")
class UserRoles(
@PrimaryKey val id
var userId:String,
var roleId:String
)
我的 View 中需要的 pojo 类
class user(
var id:String,
var name:String,
.... other fields
var roles: List<Role>
)
在我的
ViewModel
我怎样才能通过 user
结果为 LiveData
还有List<Role>
填充?从一般的方式来看,我可以:
UserDao.getUserById(id)
返回 LiveData
来自用户表和 RoleDao.getRolesForUserId(id)
返回 LiveData
包含用户的角色列表。然后在我的片段中,我可以做 viewModel.getUserById().observe{}
和 viewModel.getRolesForUserId().observe{}
.但这基本上意味着有 2 个观察员,我非常有信心这不是要走的路。 MediatorLiveData
最佳答案
使用用户及其角色创建不同的模型,并使用 @Embedded
和 @Relation
注释。
举个例子:
public class UserModel {
@Embedded
UserEntity user;
@Relation(parentColumn = "id", entityColumn = "userId", entity = UserRoles.class)
List<UserRoleModel> userRoles;
}
public class UserRoleModel {
@Embedded
UserRoles userRole;
@Relation(parentColumn = "roleId", entityColumn = "id")
List<RoleEntity> roles; // Only 1 item, but Room wants it to be a list.
}
您可以使用
UserModel
从这里。
关于android-room - 从android Room Architecture Component中的多对多结构中获取LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51614101/