用房间中的实体列表处理实体

时间:2018-11-01 22:01:20

标签: sqlite android-room

在我的应用程序中,我有对象UserPet,它具有一个“名称”,“ id”和一个PetClothe对象列表。我的PetClothe对象具有一个“名称”,“ id”和Clothe列表。我的Clothe对象具有名称和ID。

要使我的数据库与该结构匹配,我创建了实体User,Pet(在User上带有fk)和Clothe(在Clothe上带有fk)。我可以保存数据,但是不能直接从BD中检索UserPet。我必须通过多次查询数据库来手动创建它(首先是获取用户,第二是获取特定用户的宠物,第三是获取特定宠物的衣服)。我尝试了此解决方案(https://developer.android.com/reference/android/arch/persistence/room/Relation),但将其应用于我的场景时效果不佳(出现错误“错误:实体类必须使用@Entity注释”)。这是我尝试的代码:

@Entity
public class ClotheEntity
{
    @PrimaryKey
    private
    int id;
    private int petId;
    private String name;
}

@Entity
public class PetEntity
{
    @PrimaryKey
    private
    int id;
    private int userId;
}

@Entity
public class UserEntity
{
    @PrimaryKey
    private int _id;
    private String _name;
}

public class PetClothe
{
    public int _id;
    public String _name;
    public String _userId;

    @Relation(parentColumn = "_id", entityColumn = "petId")
    public List<ClotheEntity> clothes;
}

public class UserPet
{
    public int _id;
    public String _name;
    @Relation(parentColumn = "_id", entityColumn = "_userId")
    public List<PetClothe> _pet;
}

@Dao
public abstract class UserPetDao
{
    @Query("SELECT _id, _name from UserEntity")
    public abstract List<UserPet> loadUserAndPets();
}

@Database(entities = {UserEntity.class, PetEntity.class, ClotheEntity.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase
{
    public abstract UserPetDao userPetDao();
}

有人知道是否可以直接从dao检索对象UserPet吗?

谢谢您的回答。

0 个答案:

没有答案
相关问题