Let's say I want to do an INNER JOIN between two entities Foo and Bar:
@Query("SELECT * FROM Foo INNER JOIN Bar ON Foo.bar = Bar.id")List findAllFooAndBar();
Is it possible to force a return type like this?
publicclassFooAndBar{Foo foo;Bar bar;}
When I try to do that, I get this error:
error:Cannot figure out how to read this field from a cursor.
I've also tried aliasing the table names to match the field names, but that didn't work either.
If this isn't possible, how should I cleanly construct a compatible return type that includes all fields for both entities?
回答1:
Dao
@Query("SELECT * FROM Foo")List findAllFooAndBar();
Class FooAndBar
publicclassFooAndBar{@EmbeddedFoo foo;@Relation(parentColumn ="Foo.bar_id", entityColumn ="Bar.id")//Relation returns a list//Even if we only want a single Bar object .. List bar;//Getter and setter...}
This solution seems to work, but i'm not very proud of it. What do you think about it ?
Edit: An other solution
Dao, I prefer to explicit select but "*" do the job :)
@Query("SELECT Foo.*, Bar.* FROM Foo INNER JOIN Bar ON Foo.bar = Bar.id")List findAllFooAndBar();
Class FooAndBar
publicclassFooAndBar{@EmbeddedFoo foo;@EmbeddedBar bar;//Getter and setter...}
回答2:
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):
@DaopublicinterfaceFooBarDao{@Query("SELECT foo.field1 AS unique1, bar.field1 AS unique2 "+"FROM Foo INNER JOIN Bar ON Foo.bar = Bar.id")publicList getFooBars();staticclassFooBar{publicString unique1;publicString unique2;}}
You can try @Embedded annotations on foo and bar. That will tell Room to try to take the columns from your query and pour them into foo and bar instances. I have only tried this with entities, but the docs indicate that it should work with POJOs as well.
However, this may not work well if your two tables have columns with the same name.