Android Room加入的返回类型 [英] Return type for Android Room joins

查看:505
本文介绍了Android Room加入的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要在两个实体FooBar之间做一个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?

推荐答案

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?

修改:另一种解决方案

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();

Class FooAndBar

public class FooAndBar {
    @Embedded
    Foo foo;

    @Embedded
    Bar bar;

    //Getter and setter...
}

自版本2.2.0-alpha01起,room @Relation批注可以管理一对一关系

edit: since Version 2.2.0-alpha01, room @Relation annotation can manage One-To-One relation

这篇关于Android Room加入的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆