How to work with nested relationships in Room

醉酒当歌 提交于 2019-12-03 09:58:55

问题


I have entities:

@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() {}
}

and some POJOs:

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() {}
}

with DAO:

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

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?


回答1:


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).

It is working:

public class AWithB {
    @Embedded
    public A a;

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

    public AWithB() {}
}

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() {}
}


来源:https://stackoverflow.com/questions/46395775/how-to-work-with-nested-relationships-in-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!