Android Room 加入的返回类型 [英] Return type for Android Room joins
问题描述
假设我想在两个实体 Foo
和 Bar
之间做一个 INNER JOIN
:
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<FooAndBar> 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?
推荐答案
道
@Query("SELECT * FROM Foo")
List<FooAndBar> findAllFooAndBar();
类 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?
另一种解决方案
Dao,我更喜欢明确选择,但*"会做这个工作:)
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();
类 FooAndBar
public class FooAndBar {
@Embedded
Foo foo;
@Embedded
Bar bar;
//Getter and setter...
}
从2.2.0-alpha01版本开始,房间@Relation注解可以管理一对一关系
edit: since Version 2.2.0-alpha01, room @Relation annotation can manage One-To-One relation
这篇关于Android Room 加入的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!