Return type for Android Room joins
Dao
@Query("SELECT * FROM Foo")
List<FooAndBar> findAllFooAndBar();
Class FooAndBar
public class FooAndBar {
@Embedded
Foo foo;
@Relation(parentColumn = "Foo.bar_id", entityColumn = "Bar.id")
List<Bar> bar;
// If we are sure it returns only one entry
// Bar bar;
//Getter and setter...
}
This solution seems to work, but I'm not very proud of it. What do you think about it?
Edit: Another solution
Dao, I prefer to explicitly select but "*" will do the job :)
@Query("SELECT Foo.*, Bar.* FROM Foo INNER JOIN Bar ON Foo.bar = Bar.id")
List<FooAndBar> findAllFooAndBar();
Class FooAndBar
public class FooAndBar {
@Embedded
Foo foo;
@Embedded
Bar bar;
//Getter and setter...
}
edit: since Version 2.2.0-alpha01, room @Relation annotation can manage One-To-One relation
Another option is to just write a new POJO representing the resulting structure of your JOIN query (which even supports column renaming to avoid clashes):
@Dao
public interface FooBarDao {
@Query("SELECT foo.field1 AS unique1, bar.field1 AS unique2 "
+ "FROM Foo INNER JOIN Bar ON Foo.bar = Bar.id")
public List<FooBar> getFooBars();
static class FooBar {
public String unique1;
public String unique2;
}
}
See: room/accessing-data.html#query-multiple-tables