如何在会议室中处理嵌套关系 [英] How to work with nested relationships in Room

查看:90
本文介绍了如何在会议室中处理嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有实体:

@Entity
public class A {
    @PrimaryKey(autoGenerate = true)
    public long id;
    public A() {}
}

@Entity()
public class B {
    @PrimaryKey @NonNull
    public String id;
    public String oneCId;
    public String anotherCId;
    public long aId;
    public B() {}
}

@Entity
public class C {
    @PrimaryKey @NonNull
    public String id;
    public String value;
    public C() {}
}

和一些POJO:

public class AWithB {
    @Embedded
    public A a;

    @Relation(parentColumn = "id", entityColumn = "aId")
    public List<BWithC> bWithC;

    public AWithB() {}
}

public class BWithC {
    @Embedded
    public B b;
    public C oneC;
    public C anotherC;

    public BWithC() {}
}

和DAO :

@Query("SELECT * FROM a")
List<AWithB> getAllNow();

问题在于AWithB的@Relation,因为它不能指向实体以外的任何东西。但是该实体不能包括其他实体。我应该如何从数据库返回整个结构?

The problem is with the @Relation for AWithB as it cannot point to anything else than entity. But that entity cannot include other entities. How should I return the whole structure from DB?

推荐答案

似乎可以嵌套关系(文档页面上的Javadoc是出于某种原因未显示完整的代码,并因此而产生误导。)

It seems that you can have nested relations (the Javadoc on documentation page is for some reason not showing the whole code and is misleading for that reason).

正在运行:

public class AWithB {
    @Embedded
    public A a;

    @Relation(parentColumn = "id", entityColumn = "aId", entity = B.class)
    public List<BWithC> bWithC;

    public AWithB() {}
}

对于关系多对一,您仍然可以使用@Relation批注。由于某些原因,您无法获得简单的实例-您需要在此处进行收集。但这是可行的。

For relations Many To One you can still use @Relation annotation. For some reason you cannot have simple instance - you need a collection here. But it is working:

public class BWithC {
    @Embedded
    public B b;
    @Relation(parentColumn = "oneCId", entityColumn = "id")
    public Set<C> oneC;
    @Relation(parentColumn = "anotherCId", entityColumn = "id")
    public Set<C> anotherC;

    public BWithC() {}
}

这篇关于如何在会议室中处理嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆