18

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?

Andrzej Sawoniewicz
  • 1,541
  • 2
  • 16
  • 18
  • In case anyone is interested in the answer, check out this [Answer](https://stackoverflow.com/a/52554115/4980713) – Edy Daoud Dec 12 '18 at 12:17

1 Answers1

31

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() {}
}
Andrzej Sawoniewicz
  • 1,541
  • 2
  • 16
  • 18
  • Hello Andrej, Do you know how to order by the AwithB for example? – Alfonso Fernandez-Ocampo Oct 13 '17 at 10:14
  • I am not sure what do you mean. For the A table you can use normal query with `Order By` statement as well. For ordering the list of entities you got from @Relation you have to do it by yourself in your getter in your Java Bean (AWithB::getBWithCOrdered) for now at least. – Andrzej Sawoniewicz Oct 17 '17 at 08:19
  • 1
    The key here is to use the POJO as the `set` type and NOT in `@Relation(entity =..`, which seems obvious but for some reason, I though I had to. If you're going to specify the entity just like in the first example: **use the entity in the annotation and the POJO as the set / list type.** – FirstOne Sep 16 '18 at 01:44