Return type for Android Room joins

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

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?

public class FooAndBar {     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

public class FooAndBar {         @Embedded         Foo 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

public class FooAndBar {         @Embedded         Foo foo;          @Embedded         Bar 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):

@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 getFooBars();     static class FooBar {        public String unique1;        public String unique2;    } }    

See: room/accessing-data.html#query-multiple-tables



回答3:

Is it possible to force a return type like this?

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.



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