Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with nested relationships in Room

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?

like image 841
Andrzej Sawoniewicz Avatar asked Sep 24 '17 23:09

Andrzej Sawoniewicz


People also ask

Is room a relational database?

Because SQLite is a relational database, you can define relationships between entities. Even though most object-relational mapping libraries allow entity objects to reference each other, Room explicitly forbids this.

What is a room database?

Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally.

Which are not returned by the query if they are not supposed to be read from the result you can mark them with @ignore annotation?

If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.


1 Answers

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() {}
}
like image 197
Andrzej Sawoniewicz Avatar answered Sep 28 '22 05:09

Andrzej Sawoniewicz